1

我有桌子

xyz(存储用户和项目之间的关系)

| user_id |  item_id |
----------------------

一个项目可以属于一个或多个用户,反之亦然。

那么,给定user_id = Auser_id = B我如何进行 mysql 查询来选择同时属于用户 A 和用户 B 的所有项目

4

5 回答 5

4

试试这个:

SELECT Item_ID
FROM xyz
WHERE  User_ID IN ('A','B')
GROUP BY Item_ID
HAVING COUNT(distinct user_id) = 2

SQLFiddle 演示

于 2012-08-11T11:03:02.850 回答
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.

于 2012-08-11T11:04:42.673 回答
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')
于 2012-08-11T11:06:51.857 回答
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'y 方式:

select item_id
from xyz
group by item_id
having sum(case when user_id in ('A','B') then 1 end) = 2
于 2012-08-11T11:09:10.760 回答
0

一种方法可以是

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')

于 2012-08-11T12:23:15.213 回答