简体   繁体   English

sql-查找所有用户共有的项目

[英]sql - find items that ALL users have in common

I can find the items common between two given users similar to the answer here : 我可以找到两个给定用户之间共有的项目,类似于这里的答案:

SELECT items.name 
FROM   users 
       JOIN requests 
         ON users.user_id = requests.user_id 
       JOIN items 
         ON requests.item_id = items.item_id 
WHERE  users.name = 'jane'
INTERSECT
SELECT items.name 
FROM   users 
       JOIN requests 
         ON users.user_id = requests.user_id 
       JOIN items 
         ON requests.item_id = items.item_id 
WHERE  users.name = 'zaku';

I guess I could keep adding more intersect statements to include additional users and that's hardly a good solution. 我想我可以继续添加更多的相交语句以包括其他用户,这几乎不是一个好的解决方案。 How would I find any and all item(s) common among ALL users? 我如何找到所有用户共有的所有物品? In my eg, the common item among all users is "pc" but it could as well be any other item(s). 在我的例子中,所有用户之间的共同项是“ pc”,但也可以是任何其他项。 See my code on SQL Fiddle . 请参阅我在SQL Fiddle上的代码 Thanks. 谢谢。

You can try something like this: 您可以尝试如下操作:

SELECT items.name 
FROM   users 
       JOIN requests 
         ON users.user_id = requests.user_id 
       JOIN items 
         ON requests.item_id = items.item_id
GROUP BY items.name
having count(items.name) = (select count(distinct user_id) from users)

The idea is to take the count of the item from your query, and to compare it to the total count of users. 这个想法是从您的查询中获取项目的计数,并将其与用户总数进行比较。 If its equals then it means that all users has it. 如果等于,则表示所有用户都拥有它。

To get the items, you could simply do: 要获得物品,您可以简单地执行以下操作:

select r.item_id
from requests r
group by r.item_id
having count(distinct r.user_id) = (select count(*) from users);

Getting the name is essentially the same thing: 获得名称本质上是相同的:

select i.name
from requests r join
     items i
     on r.item_id = i.item_id
group by i.name
having count(distinct r.user_id) = (select count(*) from users);

This is a similar solution as @sagi who beat me to the answer. 这与@sagi击败我的答案类似。 This approach has as advantage that it can handle duplicate item_names for an user, for example, if there are two request from an user for the same item, however, this may not be applicable to your case: 这种方法的优势在于它可以为用户处理重复的item_names ,例如,如果用户有两个相同的项目请求,但是,这可能不适用于您的情况:

SELECT  item_name
FROM    (SELECT users.name AS users_name ,
                items.name AS item_name
        FROM    users
                JOIN requests ON users.user_id = requests.user_id
                JOIN items ON requests.item_id = items.item_id
        GROUP BY users.name ,
                 items.name
        HAVING  COUNT(*) > 0
       )
GROUP BY item_name
HAVING  COUNT(*) = ( SELECT COUNT(distinct user_id) FROM   users)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM