【问题标题】:SQL - Get boolean values for each matching fieldSQL - 获取每个匹配字段的布尔值
【发布时间】:2015-03-06 20:36:27
【问题描述】:

我需要有关 SQL 请求的帮助。

我有 3 张桌子:

用户

id  name
1   Jon
2   Jack
3   Bill

表格类型

id  name
1   View
2   Edit
3   Delete

id  user  type
1   1     1
2   1     2
3   1     3
4   2     1
5   3     1

所以表 Right 包含链接的用户类型对。我需要一个获取用户名的请求,以及表 Type 中每个 enrty 的布尔 (BIT) 值,该用户存在于 Right 表中。我的示例表是这样的:

Username  View  Edit  Delete
Jon       1     1     1
Jack      1     0     0 
Bill      1     0     0

非常感谢您!

【问题讨论】:

  • 这是 SQL Server 还是 MySQL?它们是完全不同的产品。
  • 这是 MySQL,我删除了错误的标签,谢谢。

标签: mysql sql


【解决方案1】:

未经测试:

select name,
       coalesce(select 1 from `right` where `type` = 1 and right.user = user.id, 0) as `View`,
       coalesce(select 1 from `right` where `type` = 2 and right.user = user.id, 0) as `Edit`,
       coalesce(select 1 from `right` where `type` = 3 and right.user = user.id, 0) as `Delete`
from User

或者:

select name, coalesce(RVIEW.R, 0) as `View`, coalesce(REDIT.R, 0) as `Edit`, coalesce(RDEL.R, 0) as `Delete`
from User
left join (select 1 R from `right` where `type` = 1) RVIEW on (right.user = user.id)
left join (select 1 R from `right` where `type` = 2) REDIT on (right.user = user.id)
left join (select 1 R from `right` where `type` = 3) RDEL on (right.user = user.id)

【讨论】:

    【解决方案2】:

    在您的示例中,您使用保留字作为表名。

    如果您想了解有关表名命名约定的更多信息,请查看 Stack Overflow here 上一个早期问题中的链接

    下面的示例显示了获取所需数据的另一种方法(表的其他名称):

    select  person.name as Username
    ,       max( if( person_right.type_id = 1, 1, 0 ) ) as `View`
    ,       max( if( person_right.type_id = 2, 1, 0 ) ) as `Edit`
    ,       max( if( person_right.type_id = 3, 1, 0 ) ) as `Delete`
    
    from person
    
    left outer join person_right
    on person_right.user_id = person.id
    
    group by person.name
    order by person.id
    

    另一件可能值得关注的是数据模型, 因为权利通常是相当“固定的”。

    如果有人不小心更改了 Type 表中的某个名称,您可能会遇到严重的安全问题。

    您可以做的是将 person_right 表更改为如下所示

    windowid  user_id  view_access  edit_access  delete_access
    1         1        1            1            1
    1         2        1            0            0
    1         3        1            0            0
    

    其中主键是 window_id+user_id 允许您在应用程序的特定窗口/部分中为每个用户设置不同的权限。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多