MySQL选择查询ANDed同一列的多个条件

时间:2015-02-17 17:55:16

标签: mysql

我有下面的测试表,表中包含以下行。

table: test_set(id (pk), pid int, fc int, fl int)

pid      fc    fl
1        7     30
1        8     31
1        9     35
2        7     39
2        8     40

现在如果我跑

SELECT pid FROM test_set WHERE fl=30 OR fl=35 GROUP BY pid;
#Result :
pid
---
1

正如所料,但如果我想跑

SELECT pid FROM test_set WHERE fl=30 AND fl=35 GROUP BY pid;
#Result :
result set (0) # Nothing matched!

这也和预期的一样,但我想在这里超出预期。我的逻辑是 fl = 30 fl = 35 共有 pid = 1 ,即当它们相交时,它们会发生pid = 1

因此,具体来说,我需要fl列的多个值的结果,这些值的一个或多个 pid 是共同的。

我已经阅读了此this并在那里发表了评论。

1 个答案:

答案 0 :(得分:1)

怎么样:

SELECT pid, COUNT(DISTINCT fl) AS count, GROUP_CONCAT(DISTINCT fl) list
FROM test_set
GROUP BY pid HAVING count > 1;

输出:

+------+-----------+------------------+
| pid  | count     | list             |
+------+-----------+------------------+
|    1 |         3 | 30,31,35         |
|    2 |         2 | 39,40            |
+------+-----------+------------------+

给出两个fl值:

SELECT pid, COUNT(DISTINCT fl) AS count
FROM test_set
WHERE fl IN (30, 35)
GROUP BY pid HAVING count = 2;

输出:

+------+-------+
| pid  | count |
+------+-------+
|    1 |     2 |
+------+-------+

给出三个fl值:

SELECT pid, COUNT(DISTINCT fl) AS count
FROM test_set
WHERE fl IN (30, 31, 35)
GROUP BY pid HAVING count = 3;

输出:

+------+-------+
| pid  | count |
+------+-------+
|    1 |     3 |
+------+-------+

pidfl上建立索引是件好事。