4

我有这个 MySQL 查询

SELECT perms.permission_id, perms.long_title, perms.category, gperms.value FROM
acl_permissions AS perms JOIN acl_group_permissions AS gperms ON
(perms.permission_id = gperms.permission_id AND gperms.group_id = 1) WHERE
perms.type IN ('adm', 'cs') AND perms.simple_title NOT IN ('adm_', 'cs_')
ORDER BY perms.long_title

基本上导致问题的位在ON. 我希望查询根据 where 条件返回所有行,perms而不管是否有行匹配gperms.group_id = 1

gperms.value如果没有行匹配,理想情况下只是一个空字符串gperms.group_id = 1

4

1 回答 1

6

您想要LEFT OUTER JOIN(或LEFT JOIN简称)gperms 而不仅仅是直接连接

SELECT perms.permission_id, perms.long_title, perms.category, gperms.value 
FROM acl_permissions AS perms 
LEFT JOIN acl_group_permissions AS gperms 
    ON (perms.permission_id = gperms.permission_id AND gperms.group_id = 1) 
WHERE perms.type IN ('adm', 'cs') 
    AND perms.simple_title NOT IN ('adm_', 'cs_')
ORDER BY perms.long_title

NULL对于在给定条件下不加入 gperms 的任何行,它将返回gperms.value。

如果你想要一个空字符串而不是NULL你可以使用IFNULL()

SELECT perms.permission_id, perms.long_title, perms.category, IFNULL(gperms.value,'')
于 2012-09-04T23:03:25.823 回答