如何读取与同一字段中多个值匹配的记录?

时间:2018-10-17 01:28:12

标签: mysql

我正在尝试读取与同一字段中多个值匹配的记录。 表格示例:A

UserID  License
1   DOG
1   CAT
1   FISH
2   DOG
2   CAT
3   FISH
4   CAT
4   DOG
4   FISH
5   CAT
5   FISH

如何提取具有三个DOG,CAT和FISH许可证的UserID?

我不确定在这里如何使用INNER JOIN,因为没有两个表。 最好的方法是什么?

谢谢 PG

5 个答案:

答案 0 :(得分:3)

甚至不需要考虑不必要的 INNER JOIN。让我们使用IN

SELECT UserID FROM A WHERE License IN('DOG','CAT','FISH');

注意事项,但是我仍然对此行有点困惑,尽管我该如何提取具有全部三个许可证DOG,CAT和FISH的UserID?

已编辑:这消除了我对 all 的困惑,请尝试以这种方式从输出中仅获取UserId。

SELECT UserID,count(*) as lnt FROM A WHERE 
  License IN('DOG','CAT','FISH') 
group by UserId having lnt = 3;

输出:

UserID  lnt
  1     3
  4     3

小提琴: http://sqlfiddle.com/#!9/e563ef/4

答案 1 :(得分:3)

您可以在SQL中使用case when...,如下所示:

SELECT UserID, SUM(CASE WHEN License IN ("DOG", "CAT", "FISH") THEN 1 ELSE 0 END) AS LICENSE_COUNT
FROM EXAMPLE_TABLE
GROUP BY UserID
HAVING LICENSE_COUNT = 3

答案 2 :(得分:1)

“如何提取具有三个DOG,CAT和FISH许可证的UserID?”

赞:

SELECT USERID, COUNT(*) AS LICENSE_COUNT
  FROM EXAMPLE_TABLE
  GROUP BY USERID
  HAVING COUNT(*) = 3

dbfiddle here

答案 3 :(得分:1)

尝试这样:

select userid 
from example_table 
WHERE License IN('DOG','CAT','FISH') group by user_id having count(distinct License)=3

答案 4 :(得分:1)

正如其他答案所述,最好使用IN运算符而不是Join。即使不使用group by或HAVING,也可以获得所需的结果。试试这个

Select DISTINCT(UserId) from A 
Where UserID IN(Select userId from A where License='DOG') 
AND UserID IN (Select UserId from A where License='CAT') 
AND UserID IN (Select UserId from A where License='FISH')