使用 UNION SELECT 时删除重复结果

发布于 2024-12-08 01:20:25 字数 605 浏览 0 评论 0原文

我遇到了 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无悔心 2024-12-15 01:20:25

GROUP BY 也没有帮助

真的吗?你这样尝试过吗?

SELECT id, MAX(qty) AS qty
FROM
(
    SELECT id, qty FROM table1
    UNION ALL
    SELECT id, qty FROM table2
) T1
GROUP BY id

GROUP BY didnt help either

Really? Did you try like this?

SELECT id, MAX(qty) AS qty
FROM
(
    SELECT id, qty FROM table1
    UNION ALL
    SELECT id, qty FROM table2
) T1
GROUP BY id
溺深海 2024-12-15 01:20:25

您可以使用 UNION DISTINCT。也许它运行...

SELECT * FROM t1 WHERE ...

UNION DISTINCT

SELECT * FROM t2 WHERE ...

You can use UNION DISTINCT. Maybe it runs...

SELECT * FROM t1 WHERE ...

UNION DISTINCT

SELECT * FROM t2 WHERE ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文