我有一张如下表格。
ID NAME
1 JOHN
2 JANE
3 JACK
在一个简单的select语句中,如何从表中查询JOHN和JANE?
条件是:
我。结果必须返回JOHN和JANE。
II。如果从表中删除了JOHN或JANE,它将只返回空结果。
答案 0 :(得分:3)
您可以使用GROUP BY/HAVING
确保有2个匹配项:
SELECT Name
FROM T
WHERE Name IN ('JOHN', 'JANE')
AND EXISTS
( SELECT 1
FROM T
WHERE Name IN ('JOHN', 'JANE')
HAVING COUNT(DISTINCT Name) = 2
);
或者你可以使用自我加入:
SELECT a.Name
FROM T a
INNER JOIN T b
ON a.Name != b.Name
WHERE a.Name IN ('JOHN', 'JANE')
AND b.Name IN ('JOHN', 'JANE');
<强> Examples on SQL Fiddle (MySQL) 强>
答案 1 :(得分:0)
试试这个:
SELECT
GROUP_CONCAT( `NAME` ) as names
FROM `TABLE`
WHERE 1
AND NAME IN ('JOHN','JANE')
HAVING names= 'JOHN,JANE'
答案 2 :(得分:0)
JohnAndJaneBothExist()
2
SELECT * FROM TABLENAME
WHERE
JohnAndJaneBothExist and
Name In ('John', 'Jane')