加入和多重条件

时间:2014-09-23 21:16:35

标签: mysql sql symfony1 doctrine-1.2

我有用户表

ID     NAME
1      John
2      Mike
3      Jack

和包含属性和用户ID的表

USER   ATTRIBUTE
1      1
1      2
2      4

我需要选择属性为1和2的所有用户(因此,在此示例中为用户#1 John)。属性可以超过两个。

我试过

SELECT * FROM user u LEFT JOIN attributes a ON u.id = a.user 
WHERE a.attribute = 1 AND a.attribute = 2

但当然不起作用..

4 个答案:

答案 0 :(得分:2)

您需要使用IN()GROUP BY ... HAVING的组合来实现此目的。如果你需要的只是用户ID,也不需要加入。如下所示:

SELECT user, COUNT(attribute) AS attribute_count
FROM attributes
WHERE attribute IN(...) /* include your set of attributes here */
GROUP BY user
HAVING attribute_count = ? /* include number equal to number of attribute ID's in IN() above */

如果您需要用户ID和名称,您只需将上述查询派生的记录集作为过滤器加入到users表中:

SELECT user.id, user.name
FROM user
INNER JOIN
  (
    SELECT user, COUNT(attribute) AS attribute_count
    FROM attributes
    WHERE attribute IN(...) /* include your set of attributes here */
    GROUP BY user
    HAVING attribute_count = ? /* include number equal to number of attribute ID's in IN() above */
  ) AS filter
  ON user.id = filter.user

答案 1 :(得分:0)

having子句可以与sum一起使用

SELECT u.id FROM user u 
INNER JOIN attributes a ON u.id = a.user 
group by u.id
having ( sum(case when attribute in (1,2) then 1 else 0 end) ) =2

答案 2 :(得分:0)

您正在寻找EXIST属性1 2的所有用户。解决此问题的一种方法 - 顾名思义 - 是EXISTS子句:

select * 
from users u
where exists
(
  select *
  from user_attributes ua
  where ua.user = u.id
  and ua.attribute = 1
)
and exists
(
  select *
  from user_attributes ua
  where ua.user = u.id
  and ua.attribute = 2
);

另一种方法是:找到具有这两个属性的所有用户ID,然后从users表中选择。

select *
from users
where id in
(
  select user
  from user_attributes
  where attribute in (1,2)
  group by user
  having count(*) = 2 
);

如果属性中存在重复条目,则必须将count(*)替换为count(distinct attribute)

还有其他方法可以解决这个问题。我认为提到的这两个是相当简单的。

答案 3 :(得分:0)

你需要一个小组......有

SELECT u.name
FROM
    users u
JOIN
    attributes a
    ON u.id = a.user
WHERE a.id IN (1,2)
GROUP BY u.name
    HAVING COUNT(*) = 2