我有桌子
xyz(存储用户和项目之间的关系)
| user_id | item_id |
----------------------
项目可以属于一个或多个用户,反之亦然。
所以,鉴于 user_id = A 和 user_id = B ,如何选择mysql查询来选择属于的所有 项目用户A和用户B ?
答案 0 :(得分:4)
试试这个:
SELECT Item_ID
FROM xyz
WHERE User_ID IN ('A','B')
GROUP BY Item_ID
HAVING COUNT(distinct user_id) = 2
答案 1 :(得分:1)
SELECT a.item_id
FROM xyz AS a
JOIN xyz AS b
ON b.item_id = a.item_id
WHERE a.user_id = 'A'
AND b.user_id = 'B' ;
如果(user_id, item_id)
的组合不唯一,请将其SELECT DISTINCT
。
答案 2 :(得分:1)
另一种选择:
select item_id from xyx
where item_id IN(select item_id from xyz where user_id ='A')
and item_id IN(select item_id from xyz where user_id ='B')
答案 3 :(得分:1)
这就足够了:http://sqlfiddle.com/#!2/63ad5/6
select item_id
from xyz
group by item_id
having sum(user_id in ('A','B')) = 2
ANSI SQL的方式:
select item_id
from xyz
group by item_id
having sum(case when user_id in ('A','B') then 1 end) = 2
答案 4 :(得分:0)
一种方法可以是
SELECT temp1.item_id FROM ( SELECT DISTINCT item_id FROM pcadminlogging WHERE userid ='A' ) AS temp1 加入( SELECT DISTINCT item_id FROM pcadminlogging WHERE userid ='B' ) AS temp2 ON temp1.item_id = temp2.item_id 哪里 temp1.userid in('A','B')