仅选择表格中的公共字段

时间:2014-05-18 09:20:10

标签: mysql sql

我想实现一些“权限”管理,只显示结果集中设置为public的字段。字段的名称以及它的公共或私有是否存储在第二个表中。

"select user.id, user.firstname, user.lastname, user.email 
 from users where (user.id = '30')"

现在表权限看起来像

id / user_id / fieldname / type
1 / 30 / users.lastname / private
2 / 30 / users.firstname / public
3 / 30 / users.eMail / private
4 / 31 / users.lastname / private 
(...)

有没有办法将它放在一个查询中?我的另一个选择是运行查询并使用PHP循环,我认为这不是很好。

我有这样的想法:

Select users.firstname if (select typ from rights where user_id = users.id and fieldname =     
'users.firstname') = 'public', users.lastname if (select typ from rights where user_id = 
users.id and fieldname = 'users.lastname') = 'public'

因此结果将是整行,但设置为private的字段将不包含任何数据。

2 个答案:

答案 0 :(得分:1)

JOIN表:

SELECT U.id, U.firstname, U.lastname, U.email 
FROM users U JOIN
     rights R ON U.id=R.user_id
WHERE R.type='public'

详细了解JOIN here

如果您想查看user_id

SELECT U.id, U.firstname, U.lastname, U.email 
FROM users U JOIN
     rights R ON U.id=R.user_id
WHERE R.type='public'
  AND U.id=30

答案 1 :(得分:1)

我读了一下你的评论,你可以这样做:

SELECT U.id
    , U.firstname
    , CASE WHEN R.type IS NOT NULL THEN U.lastname ELSE NULL END as lastname
    , U.email 
FROM users U 
    LEFT JOIN rights R 
        ON U.id=R.user_id
        AND R.type='public'

编辑根据上次提问更新

SELECT U.id
    , CASE WHEN RFirstName.user_id IS NOT NULL THEN U.firstname ELSE NULL END as firstname
    , CASE WHEN RLastName.user_id IS NOT NULL THEN U.lastname ELSE NULL END as lastname
    , CASE WHEN REmail.user_id IS NOT NULL THEN U.email ELSE NULL END as email 
FROM users U 
    LEFT JOIN rights RFirstName
        ON U.id=RFirstName.user_id
        AND RFirstName.type='public'
        AND RFirstName.fieldname = 'users.firstname'
    LEFT JOIN rights RLastName
        ON U.id=RLastName.user_id
        AND RLastName.type='public'
        AND RLastName.fieldname = 'users.lastname'
    LEFT JOIN rights REmail
        ON U.id=REmail.user_id
        AND REmail.type='public'
        AND REmail.fieldname = 'users.eMail'