从单列中选择多个值

时间:2013-01-20 09:24:16

标签: mysql sql select

我想从数据库表中的单个列中选择多个值,这些值等于多个值。我希望所有这些值匹配,否则它应该不返回任何行。我不想使用“IN”,因为它等于“OR”。

以下是它应该做什么的基本模型,但它需要是动态的,因为我希望将它与PDO语句一起使用。如果数据库只包含id的1和2,则它应该失败,即不返回任何行。

SELECT
id
FROM
reports
WHERE
id=1 AND id=2 AND id=3

我有如下的当前代码,它错误地返回零行:

SELECT id,title
FROM reports
WHERE id IN (1,2)
GROUP BY title 
HAVING COUNT(DISTINCT id) = 2

我目前的表格结构如下: http://www.sqlfiddle.com/#!2/ce4aa/1

1 个答案:

答案 0 :(得分:4)

您必须使用HAVING COUNT(id) = 3来确保所选行包含所有三个ID。类似的东西:

SELECT *
FROM reports
WHERE id = 1 OR id = 2 OR id = 3 -- Or id IN(1, 2, 3)
GROUP BY SomeOtherField
HAVING COUNT(DISTINCT id) = 3;

SELECT *
FROM reports
WHERE SomeOtherField IN (SELECT SomeOtherField 
                         FROM reports
                         WHERE id = 1 or id = 2 -- Or id IN(1, 2, 3)
                         GROUP BY SomeOtherField
                         HAVING COUNT(DISTINCT id) = 3
                        );

请注意:您必须GROUP BY SomeOtherField其中SomeOtherField是除id之外的其他字段,因为如果您GROUP BY id HAVING COUNT(id)你不会得到任何记录,因为COUNT(id)总是= 1。

修改:已修复WHERE子句,OR代替AND

SQL Fiddle Demo