MySQL 按问题分组
我有一个票证表,需要选择与某个用户不关联的唯一票证列表。我不能只说“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 |
+----+---------+--------+
有人可以帮助我构建一个查询来返回我需要的结果吗?
谢谢你!
I have a table of tickets and need to select a unique list of tickets that a certain user is not associated with. I cannot just say "WHERE user_id != 10" because the GROUP BY statement affects which user_id is returned.
Lastly, I am working with a MySQL database.
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 |
+----+---------+--------+
Can someone help me build a query to return my needed results?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该可以解决问题:
这会从票证表中选择与用户 (id = 10) 拥有的票证不匹配的所有票证。
GROUP BY 子句旨在(如 OrangeDog 所说)用于聚合查询。例如,如果您要查找票证的用户数量,您可以使用:
这将为您提供:
因为您在这里没有做类似的事情,所以没有必要。
This should do the trick:
This selects all the tickets from the ticket table that don't match the tickets that the user (id = 10) has.
The GROUP BY clause is meant to be used (as OrangeDog said) for aggregate queries. So for example, if you were going to find the number of users for a ticket, you would use:
Which would give you:
Since you're not doing something like that here, it's not necessary.
GROUP BY
适用于使用聚合函数(COUNT
、SUM
等)。如果你不这样做,它通常不会做任何有用的事情。GROUP BY
is for when you're using aggregate functions (COUNT
,SUM
, ect.). It usually won't do anything useful if you're not.