简体   繁体   English

从单列中选择多个值

[英]Select Multiple Values From Single Column

I would like to select multiple values from a single column in a database table that equal to a number of values. 我想从数据库表中的单个列中选择多个值,这些值等于多个值。 I want all these values to match otherwise it should return no rows. 我希望所有这些值匹配,否则它应该不返回任何行。 I do not want to use "IN" as that is equal to "OR". 我不想使用“IN”,因为它等于“OR”。

The following is a basic mockup of what it should do but it needs to be dynamic as I wish to use it with a PDO statement. 以下是它应该做什么的基本模型, 但它需要是动态的,因为我希望将它与PDO语句一起使用。 If the database only contains id's 1 and 2 it should fail ie return no rows. 如果数据库只包含id的1和2,则它应该失败,即不返回任何行。

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

I have the current code as follow which is incorrectly returning zero rows: 我有如下的当前代码,错误地返回零行:

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

My current table structure is as follows: http://www.sqlfiddle.com/#!2/ce4aa/1 我目前的表格结构如下: http//www.sqlfiddle.com/#!2 /ce4aa / 1

You have to use HAVING COUNT(id) = 3 to ensure that the selected rows have all the three id's. 您必须使用HAVING COUNT(id) = 3来确保所选行具有所有三个id。 Something like: 就像是:

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;

Or: 要么:

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
                        );

Note that: You have to GROUP BY SomeOtherField where SomeOtherField is other field than id because if you GROUP BY id with HAVING COUNT(id) you won't get any records, since COUNT(id) will be always = 1. 请注意:您必须使用GROUP BY SomeOtherField ,其中SomeOtherField是除id之外的其他字段,因为如果您使用HAVING COUNT(id) GROUP BY id ,则不会获得任何记录,因为COUNT(id)将始终为= 1。

Edit: fixed WHERE clause, OR 's instead of AND 's. 编辑:修复WHERE子句, OR代替AND代替。

SQL Fiddle Demo SQL小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM