我有以下三张表:
templatesubscription <
table template:
id | name
table user
id | name | ...
table templatesubscriptions
id | template_id | user_id现在,我想检查当前登录的用户(用户ID = 10)是否可以使用ID = 0编辑模板。只有当用户有此模板的模板订阅时,他才能编辑它。
现在我可以问两个问题了。首先,我将使用模板id获取当前用户的模板订阅:
SELECT * FROM templatesubscription WHERE user_id = 10 AND template_id = 0现在我可以检查返回值是否为null,如果是,用户将得到一条错误消息。如果结果不是空的,我将得到模板表的模板:
SELECT * FROM templates WHERE id = 0但这种方法对我来说并不是很好。我能把这两种说法合并在一起吗?如果用户没有此模板的模板订阅,则返回值应为模板或null。
发布于 2019-04-08 09:08:30
您可以使用where条件将两者结合在一起。只要用户有权限,就会有输出。
SELECT *
FROM templates
WHERE id = 0 and 1=(SELECT 1 FROM templatesubscription WHERE user_id = 10 AND template_id = 0)发布于 2019-04-08 09:08:40
学习有关联接的知识,here's a good overview。
因此,在您的示例中,您希望在订阅和模板之间进行内部连接,以便只获得用户可以访问的订阅:
SELECT t.* -- it's better to list all the columns than use *
FROM templates t
INNER
JOIN templatesubscription ts
ON t.id = ts.template_id
WHERE ts.user_id = 10
AND ts.template_id = 0因此,只有在templates表的templatesubscription中有该user_id的记录时,这才会返回该行。
https://stackoverflow.com/questions/55569754
复制相似问题