Removing duplicate results when using UNION SELECT

I am having a problem with a MySQL query.

Let's say we have two tables:

id qty

eleven

2 ...... 1

3 ...... 1

4 ...... 3

and

id qty

12

2 ...... 1

6 ...... 1

7 ...... 2

What I really need to get is a result filtered by id, so there are no duplicate identifiers. If they are two identical identifiers, only the identifier with a higher qty number will be taken into account. Therefore, in an ideal situation, I get this result:

id qty

12

2 ...... 1

3 ...... 1

4 ...... 3

6 ...... 1

7 ...... 2

SOION SELECT, , , , . GROUP BY . PHP, , MySQL.

, !

+5
2

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
+15

UNION DISTINCT. , ...

SELECT * FROM t1 WHERE ...

UNION DISTINCT

SELECT * FROM t2 WHERE ...
+11

All Articles