选择查询(一个表)

时间:2013-11-12 16:54:54

标签: mysql sql

我的数据库中有表Pruza,例如:

SifVU     Name
1         Test1
2         Test2
1         Test3
2         Test3

如何使Select查询仅返回Test3,因为只有Test3同时具有Sif(1和2)。

3 个答案:

答案 0 :(得分:1)

试试这个,它只显示有SifVU 1和2的名字:

select one.name
from (select name from Pruza where SifVU = 1) one
join (select name from Pruza where SifVU = 2) two
on (one.name = two.name)

答案 1 :(得分:1)

SELECT Name
FROM Pruza
WHERE SifVU in (1,2)
GROUP BY Name
HAVING COUNT(DISTINCT SifVU) = 2

请参阅fiddle

答案 2 :(得分:0)

这可以用于任何数量的TEST3类型的记录,不需要任何硬编码

SELECT B.NAME
FROM
(SELECT COUNT(SifVU) AS CNT_SifVU FROM TABLE GROUP BY SifVU) AS A
INNER JOIN 
(
SELECT COUNT(*) AS DISTINCT_SIFVU, NAME
FROM
(SELECT DISTINCT SifVU, Name FROM TABLE) AS B
) AS C
ON B.DISTINCT_SIFVU = A.CNT_SifVU