我有桌子
xyz(存储用户和项目之间的关系)
| user_id | item_id |
----------------------
一个项目可以属于一个或多个用户,反之亦然。
那么,给定user_id = A和user_id = B我如何进行 mysql 查询来选择同时属于用户 A 和用户 B 的所有项目?
试试这个:
SELECT Item_ID
FROM xyz
WHERE User_ID IN ('A','B')
GROUP BY Item_ID
HAVING COUNT(distinct user_id) = 2
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
.
另外一个选项:
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')
这就足够了: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'y 方式:
select item_id
from xyz
group by item_id
having sum(case when user_id in ('A','B') then 1 end) = 2
一种方法可以是
SELECT temp1.item_id FROM (SELECT DISTINCT item_id FROM pcadminlogging WHERE userid='A') AS temp1 JOIN (SELECT DISTINCT item_id FROM pcadminlogging WHERE userid='B') AS temp2 ON temp1.item_id=temp2.item_id WHERE temp1.userid in ( 'A','B')