[英]SQL Selecting rows with multiple values
I have these 2 tables: 我有这两个表:
Table SW_ITEM
: 表
SW_ITEM
:
ID SWID ITEM_ID
1 1 99
2 2 99
3 5 99
4 2 100
5 1 100
6 1 101
7 2 102
Table ITEM
: 表
ITEM
:
ID FILENAME
99 abc
100 def
101 geh
102 ijk
column ITEM_ID
is a foreign key to the column ID
of table ITEM
. 列
ITEM_ID
是表ITEM
的列ID
的外键。
So I want all filenames which have the SWID "1" AND "2" (that would be ITEMID 99 and 100, so their filenames are "abc" and "def") 所以我想要所有SWID为“1”和“2”的文件名(即ITEMID 99和100,所以他们的文件名是“abc”和“def”)
Here I have to say that it is possible that ITEM_ID
has more than one entry with the same SWID, so I cannot use this SQL: 在这里我不得不说
ITEM_ID
有可能有多个具有相同SWID的条目,所以我不能使用这个SQL:
SELECT ITEM_ID FROM SW_ITEM
WHERE SWID IN (1,2)
GROUP BY ITEM_ID
HAVING COUNT(ITEM_ID) = 2
So is there any other possibility to get all entries which have the SWID 1 and 2 (creating a join for every SWID is also not an option - because with many entries it would be really slow) 那么有没有其他可能获得具有SWID 1和2的所有条目(为每个SWID创建连接也不是一个选项 - 因为有很多条目它会非常慢)
Kind regards 亲切的问候
You need to use DISTINCT
in COUNT
and count SWID
instead of ITEM_ID
: 您需要在
COUNT
使用DISTINCT
并计算SWID
而不是ITEM_ID
:
SELECT ITEM_ID FROM SW_ITEM
WHERE SWID IN (1,2)
GROUP BY ITEM_ID
HAVING COUNT(DISTINCT SWID) = 2;
Please checkout this demo . 请查看此演示 。
To retrieve all filenames, try: 要检索所有文件名,请尝试:
SELECT ITEM_ID, FILENAME
FROM ITEM JOIN SW_ITEM ON ITEM.ID = SW_ITEM.ITEM_ID
WHERE SWID IN (1,2)
GROUP BY ITEM_ID
HAVING COUNT(DISTINCT SWID) = 2;
I have a little different problem where I have to find a person with multiple entries in the same table based on email for that the above solution didn't work for me. 我有一个不同的问题,我必须在同一个表中找到一个基于电子邮件的多个条目的人 ,因为上述解决方案对我不起作用。 You can try using the following,
您可以尝试使用以下内容,
SELECT person_id,
(ROW_NUMBER () OVER (PARTITION BY pers_email ORDER BY pers_name) person_count
from pers_table
WHERE person_count > 2;
Try this hope it works :) 试试这个希望它有效:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.