I have 2 tables
tableA
:
id | dateA | colA | … |
---|---|---|---|
1 | 2022-11-11 12:00:00 | A | |
2 | 2022-11-12 12:00:00 | B | |
3 | 2022-11-14 12:00:00 | C |
tableB
:
id | dateB | colB | … |
---|---|---|---|
3 | 2022-11-05 12:00:00 | D | |
4 | 2022-11-06 12:00:00 | E | |
5 | 2022-11-13 12:00:00 | F |
and I want put all rows to one result and sort it by column date
Wanted result (rows from both tables sorted by column date DESC
):
id | date | colA | colB | … | … |
---|---|---|---|---|---|
3 | 2022-11-14 12:00:00 | C | |||
5 | 2022-11-13 12:00:00 | F | |||
2 | 2022-11-12 12:00:00 | B | |||
1 | 2022-11-11 12:00:00 | A | |||
4 | 2022-11-06 12:00:00 | E | |||
3 | 2022-11-05 12:00:00 | D |
I can combine tables, but tables are "squashed"…
SELECT
COALESCE(a.id, b.id) AS id,
COALESCE(a.dateA, b.dateB) AS date,
a.colA,
b.colB
FROM tableA AS a, tableB AS b
ORDER BY date DESC
2
Answers
Use
UNION ALL
andORDER BY
. This requires enumerating the columns:union all
combines two datasets. Since we have different columns in the two tables, we need to arrange bothselect
clauses so that they return the same set of columns ;null
values can be used to fill in "missing" columns in a given dataset.As for sorting the resultset : in MySQL, a single
ORDER BY
in aUNION ALL
query applies to the whole resultset (after it was unioned). The query just does that (usingdateX
, the column alias that was created in the subqueries).In case you want to show the rows that share same
id
anddate
as one row, you can build on top of GMB’s answer:See db-fiddle