MySQL group with with where子句的计数大于1

时间:2012-03-21 10:47:17

标签: mysql

我知道这应该非常简单,但对于我的生活,我无法得到我的查询来做我需要的事。

我希望找到按paid分组的特定状态(ref)的所有行,但前提是找到的行数超过1行。

这是我的样本表:

+-----+----------+----------+-------+
| id  | deleted  | status   |  ref  |
+-----+----------+----------+-------+
|   1 |        0 | pending  | 10001 |
|   2 |        0 | paid     | 10001 |
|   3 |        0 | paid     | 10001 |
|   4 |        0 | paid     | 10002 |
|   5 |        1 | pending  | 10002 |
|   6 |        1 | paid     | 10002 |
|   7 |        0 | pending  | 10003 |
|   8 |        0 | paid     | 10003 |
|   9 |        0 | paid     | 10003 |
|  10 |        0 | paid     | 10003 |
|  11 |        0 | pending  | 10004 |
|  12 |        0 | paid     | 10004 |
|  13 |        1 | pending  | 10005 |
|  14 |        1 | paid     | 10005 |
|  15 |        1 | paid     | 10005 |
|  16 |        0 | paid     | 10005 |
|  17 |        0 | pending  | 10006 |
|  18 |        0 | paid     | 10006 |
|  19 |        0 | paid     | 10006 |
+-----+----------+----------+-------+

这是我的SQL:

SELECT * FROM `orders`
WHERE `deleted` = 0 AND `status` = 'paid'
GROUP BY SUBSTR(`ref`,0,5)
HAVING COUNT(*) > 1
ORDER BY `id` DESC

由于ref有时包含附加数字,我需要通过SUBSTR进行匹配。

问题是我的查询返回了这个:

+-----+----------+---------+-------+
| id  | deleted  | status  |  ref  |
+-----+----------+---------+-------+
|   2 |        0 | paid    | 10001 |
+-----+----------+---------+-------+

当我希望它返回ref s 1000110003& 10006

任何人都可以帮我弄清楚我做错了吗?

由于

3 个答案:

答案 0 :(得分:18)

尝试

SELECT * FROM `orders`
WHERE `deleted` = 0 AND `status` = 'paid'
GROUP BY SUBSTR(`ref`,1,5)
HAVING COUNT(*) > 1
ORDER BY `id` DESC

SUBSTR的position-argument以1开头,而不是0。

答案 1 :(得分:8)

来自SUBSTR doc:

  

对于所有形式的SUBSTRING(),将从中提取子字符串的字符串中第一个字符的位置计为1。

所以试试这个:

SELECT * FROM `orders`
WHERE `deleted` = 0 AND `status` = 'paid'
GROUP BY SUBSTR(`ref`,1,5)
HAVING COUNT(*) > 1
ORDER BY `id` DESC

答案 2 :(得分:0)

查询应该是

SELECT * from order
WHERE status="paid"
GROUP BY SUBSTRING('ref',1,5)
HAVING COUNT(*) > 1;