使用 UNION SELECT 时删除重复结果
我遇到了 MySQL 查询问题。
假设我们有两个表:
id qty
1......1
2......1
3......1
4......3
和
id qty
1...... ..2
2......1
6......1
7......2
我实际需要得到的是按id过滤的结果,所以不存在重复的id。如果它们是两个相同的 id,则仅考虑数量较大的 id。因此,在理想情况下,我会得到以下结果:
id qty
1......2
2......1
3......1
4......3
6.... ..1
7......2
到目前为止我尝试的是 UNION SELECT,它工作得很好,但是当遇到重复的 ID 时,它不会删除重复项,因为它只删除重复的行。 GROUP BY 也没有帮助。我仍然可以通过 PHP 中的数组对此进行排序,但如果可能的话,我希望在 MySQL 级别进行排序。
感谢大家的帮助,非常感谢!
Ive got a problem with a MySQL query.
Let's say, we have two tables:
id qty
1......1
2......1
3......1
4......3
and
id qty
1......2
2......1
6......1
7......2
What I actually need to get is a result filtered by id, so there are no duplicate id's. If they are two same id's, only id whith a higher qty number will be considered. So in and ideal situation I would get this result:
id qty
1......2
2......1
3......1
4......3
6......1
7......2
What Ive tried so far is a UNION SELECT, which works fine, but when it comes across a duplicate ID it wont remove duplicates, as it removes just duplicates rows. GROUP BY didnt help either. I could still sort this out through an array in PHP, but I would love having this sorted at MySQL level if possible.
Thanks everyone for you help, it's much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
真的吗?你这样尝试过吗?
Really? Did you try like this?
您可以使用 UNION DISTINCT。也许它运行...
You can use UNION DISTINCT. Maybe it runs...