【问题标题】:mySQL Schema design advisemySQL Schema 设计建议
【发布时间】:2013-07-15 12:05:16
【问题描述】:

问题:如果他们具有包含在文档中的角色,我如何使用下面的架构来获取尚未在文档上签名的用户列表?

背景:

我有一个用户表。用户具有角色。这是一个简单的设置:

Role table:           Role_ID | Name
User table:           User_ID | Name
Users_Roles table:    User_ID | Role_ID

现在我需要添加一个 Documents 表:

Documents table:  Document_ID | Name

我需要知道用户何时签署了文档:

Documents_Users table: User_ID | Document_ID

到目前为止,它非常简单。

但现在变得很难了——我需要对文档添加限制,这样我就可以将文档分配给多个角色:

即Document_ID 1 用于 Role_ID (3,4,5)。

我猜我需要这样做

Documents_Roles table: Role_ID | Document_ID

但是 - 这是我不知道的难点:如果他们具有包含在文档中的角色,我如何使用上面的架构来获取尚未在文档上签名的用户列表?

【问题讨论】:

  • 这种关系是否可以只用一个联结表来表达,即Users_Roles_Documents
  • 问题是表格如何知道用户是否没有完成文档?它只会知道他们是否已经完成了文件?
  • 我对任何和所有想法持开放态度 - 如果您认为可行,我可以试一试 - 可以更改架构以使此解决方案发挥作用...

标签: mysql schema


【解决方案1】:

Your structure is correct:

SELECT Users_Roles.User_ID, Documents_Roles.Document_ID
FROM Documents_Roles -- get some documents
-- JOIN Documents ON (Documents.Document_ID = Documents_Roles.Document_ID) -- if you need details from the Documents table
JOIN Users_Roles USING (Role_ID) -- get all users expected to sign them
-- JOIN Users ON (Users.User_ID = Users_Roles.User_ID) -- if you need details from the Users table
LEFT JOIN Documents_Users ON
    Documents_Users.Document_ID = Documents_Roles.Document_ID AND
    Documents_Users.User_ID = Users_Roles.User_ID -- find whether they have signed it
WHERE
    Documents_Users.User_ID IS NULL -- only those expected users who have *not* signed it
    -- AND Documents_Roles.Document_ID = some_id
;

【讨论】:

  • 小问题 - 如果用户有多个与文档“重叠”的角色 - 它会在 SQL 中复制它们:sqlfiddle.com/#!2/fc2da/1
  • 有什么想法可以让每个用户只得到一个结果吗?
  • @TheShiftExchange 添加DISTINCT 子句:SELECT DISTINCT blah, blah(您当然希望每个用户每个文档都有一个结果)。
  • 完美 - 谢谢 - 为了你的帮助,我为此付出了 50 赏金 - 它解决了我的头疼问题。
猜你喜欢
  • 2017-08-29
  • 1970-01-01
  • 2012-08-30
  • 2012-01-27
  • 1970-01-01
  • 2011-05-10
  • 2012-10-31
  • 2011-10-23
  • 1970-01-01
相关资源
最近更新 更多