mysql 从单个列中选择多个值

wkyowqbh  于 2023-04-10  发布在  Mysql
关注(0)|答案(2)|浏览(197)

我想从数据库表中的单个列中选择多个值,这些值等于多个值。我希望所有这些值都匹配,否则它不应该返回任何行。我不想使用“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

gk7wooem

gk7wooem1#

您必须使用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,其中SomeOtherFieldid以外的字段,因为如果你GROUP BY idHAVING COUNT(id),你不会得到任何记录,因为COUNT(id)总是= 1。
**编辑:**修复了WHERE子句,将AND替换为OR

SQL Fiddle演示

e3bfsja2

e3bfsja22#

你也可以试着跟随。

SELECT *
FROM reports
GROUP BY SomeOtherField
HAVING COUNT(DISTINCT id) = 3
and id IN(1, 2, 3)

相关问题