MySQL Group By Question

时间:2011-02-08 19:31:16

标签: mysql group-by

我有一张故障单表,需要选择某个用户未与之关联的唯一故障单列表。我不能只说“WHERE user_id!= 10”,因为GROUP BY语句会影响返回哪个user_id。

最后,我正在使用MySQL数据库。

SELECT * FROM tickets;
+----+---------+--------+
| id | user_id | ticket |
+----+---------+--------+
|  1 |      10 | T12345 |
|  2 |      11 | T23456 |
|  3 |      12 | T34567 |
|  4 |      10 | T34567 |
|  5 |      13 | T45678 |
+----+---------+--------+

SELECT * FROM tickets WHERE user_id != 10 GROUP BY ticket;
+----+---------+--------+
| id | user_id | ticket |
+----+---------+--------+
|  2 |      11 | T23456 |
|  3 |      12 | T34567 |
|  5 |      13 | T45678 |
+----+---------+--------+

-- Needed result
-- User #10 also worked with ticket T34567,
-- so I do not want it listed in the results
+----+---------+--------+
| id | user_id | ticket |
+----+---------+--------+
|  2 |      11 | T23456 |
|  5 |      13 | T45678 |
+----+---------+--------+

有人可以帮我构建一个查询来返回我需要的结果吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

SELECT *
FROM tickets
WHERE ticket NOT IN (SELECT ticket FROM tickets WHERE user_id = 10)

这将选择故障单表中与用户(id = 10)所拥有的故障单不匹配的所有故障单。

GROUP BY子句用于聚合查询(如OrangeDog所述)。例如,如果您要查找故障单的用户数,则可以使用:

SELECT COUNT(*) AS tcnt, ticket
FROM tickets
GROUP BY ticket

哪会给你:

+------+--------+
| tcnt | ticket |
+------+--------+
|    1 | T12345 |
|    1 | T23456 |
|    2 | T34567 |
|    3 | T45678 |
+------+--------+

由于你在这里没有这样做,所以没有必要。

答案 1 :(得分:0)

SELECT *
FROM tickets 
WHERE ticket NOT IN (SELECT ticket FROM tickets WHERE user_id = 10);

GROUP BY适用于使用汇总函数(COUNTSUM等)的情况。如果你不这样做,它通常不会做任何有用的事情。