mysql左连接加入所有行的条件

时间:2017-03-03 01:46:43

标签: mysql

我有两个表,fos_user和zone 与

  • fos_user {idnameenabled}
  • zone {idfos_user_idenabled}
每个fos_user

可以超过zone

我需要过滤fos_users只有zone的{​​{1}}

我尝试

enabled=1

但是我得到的SELECT * FROM fos_user as u LEFT JOIN zona as z ON u.id=z.users_id WHERE z.enabled=1 AND u.enabled=1 列表几乎只有一个带有fos_user

的区域

我该如何解决?

谢谢

2 个答案:

答案 0 :(得分:1)

您需要第二个条件来排除未启用区域中的用户。

SELECT *
FROM fos_user AS u
INNER JOIN zone AS z on u.id = z.users_id
LEFT JOIN zone AS z1 on u.id = z1.users_id AND z1.enabled = 0
WHERE u.enabled = 1 AND z.enabled = 1
AND z1.id IS NULL

您使用INNER JOIN来准确匹配区域,并使用LEFT JOIN进行NULL测试,以查找符合该条件的用户(请参阅Return row only if value doesn't exist)。

答案 1 :(得分:1)

您可以按用户分组,并将已启用区域的数量与区域总数进行比较:

SELECT *
  FROM fos_user u
  JOIN zone z ON u.id = z.users_id
 WHERE u.enabled = 1
 GROUP BY u.id
HAVING SUM(z.enabled = 1) = COUNT(*);