我有这个数据库结构
* user
user_id
name
* client
client_id
name
* user_client
user_client_id
user_id
client_id
* message
message_id
client_id
description
如果user_client
上有条目,则该用户的权限仅限于表中为其 ID 列出的特定客户端。如果没有条目,则用户可以访问任何客户端。
如何只选择用户可以阅读的消息?
我正在尝试对 WHERE 子句执行 IF 来检查 user_client
表上是否有任何条目,但我不知道从哪里开始。如果 user_client
上没有条目或仅在 user_client
表上指定 client_id
的消息,则需要选择来自任何客户端的所有消息
感谢您的帮助!
最佳答案
我建议执行两种不同的查询:一种针对 super 用户,另一种针对受限用户。然后您可以使用 UNION 将两个结果连接起来。
SELECT M.message_id,
M.client_id,
M.description
FROM message M
INNER JOIN user_client UC ON (UC.client_id = M.client_id)
INNER JOIN user U ON (UC.user_id = U.id)
WHERE U.id = :user_id
UNION
SELECT M.message_id,
M.client_id,
M.description
FROM message M
WHERE NOT EXISTS (
SELECT *
FROM user_client
WHERE user_id = :user_id
)
您可以通过其他查询获得相同的结果,但恕我直言,这个查询更清晰且更易于维护。
编辑:如果您想确保用户存在,您应该将第二个查询与用户表连接起来。
SELECT M.message_id,
M.client_id,
M.description
FROM message M
JOIN user U
WHERE U.id = :user_id
AND NOT EXISTS (
SELECT *
FROM user_client
WHERE user_id = :user_id
)
关于mySQL SELECT 帮助。如果或存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28678898/