mysql如何获得与同一列中另一个组的值匹配的组?

rsaldnfx  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(358)
Here are the tables:  

  Drinker (name, address)  
  Bar (name, address)  
  Beer (name, brewer)  
  Frequents (drinker, bar, times_a_week)  
  Likes (drinker, beer)  
  Serves (bar, beer, price)

问题是这样的:
找到那些和西尔维休谟一样喜欢啤酒的人。
我的代码如下:

SELECT *  
FROM drinker d  
JOIN likes l1 ON d.Name = l1.Drinker  
WHERE l1.Beer IN (SELECT Beer FROM likes l2 WHERE l2.Drinker = 'Silvie Hume');

好像我的输出返回了所有与西尔维休谟啤酒匹配的饮料一样,我不知道如何选择和西尔维休谟喜欢同一套啤酒的人。有什么帮助吗?谢谢!
我试着替换 IN= ALL ,但效果并不理想

dz6r00yl

dz6r00yl1#

一个选项在 Likes 表格:

SELECT
    t1.drinker
FROM Likes t1
LEFT JOIN Likes t2
    ON t1.beer = t2.beer AND t2.drinker = 'Silvie Hume'
WHERE
    t1.drinker <> 'Silver Hume'
GROUP BY
    t1.drinker
HAVING
    COUNT(*) = COUNT(t2.beer) AND
    COUNT(*) = (SELECT COUNT(*) FROM Likes WHERE drinker = 'Silvie Hume');

解释一下,第一个条件 HAVING 该条款Assert,所有给定的饮酒者的喜欢匹配西尔维休谟。第二个条件涵盖了边缘的情况下,所有给定的饮酒者的喜欢不匹配,但西尔维休姆也有一些其他的喜欢。因此,我们Assert每个饮酒者的喜好数量与西尔维休谟相同。

相关问题