MySQL A or B but NOT both

若如初见. 提交于 2019-12-31 05:09:12

问题


This seems like an easy query but I cannot seem to get it or relate it to other posts on stack overflow. Would anyone be able to explain... This is what I have so far, it is returning records for all bars where one or both people go.

TBL frequents Schema - drinker VARCHAR(50) PK, bar VARCHAR(50) PK

Bars which are frequented by John or Rebecca but not by both of them

SELECT DISTINCT bar 
FROM frequents
WHERE drinker = 'John' XOR drinker = 'Rebecca' 
  AND bar NOT IN (
    SELECT f1.bar 
    FROM frequents f1, frequents f2
    WHERE (
      f1.drinker = 'John' 
      AND f2.drinker = 'Rebecca' 
      AND f1.bar = f2.bar
    )
  );

回答1:


Something like this should satisfy the specification:

SELECT f.bar 
  FROM frequents f
 WHERE f.drinker IN ('John','Rebecca')
 GROUP 
    BY f.bar
HAVING COUNT(DISTINCT f.drinker) < 2

  • get all of bar for 'John' and/or 'Rebecca'
  • collapse the rows to a single row for each bar
  • get a count of drinker for each bar
  • discard rows that have a count of 2 (i.e. both John and Rebecca)
  • leaving only values of bar for John and not Rebecca or vice versa


来源:https://stackoverflow.com/questions/52356992/mysql-a-or-b-but-not-both

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!