PostgreSQL: How to union 3 tables sorted by date

前端 未结 2 346
小鲜肉
小鲜肉 2020-12-31 09:25

I have 3 different SQL queries from 3 different unrelated tables (all using LIMIT and ORDER BY).

I would like to merge and sort the results according to the \"date\"

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 09:41

    The best way is to create a new table containing the common fields from the three other tables and add an index on the common date field. The original three tables should contain a foreign key linking to the common table. With this design the query becomes simple:

    SELECT *
    FROM common_table
    ORDER BY "date" DESC
    LIMIT 100
    

    If you also need data from the more specific tables you can use LEFT JOINs to also select that data in the same query.

    If you can't change your design and performance is not an issue then you can use UNION ALL to combine the results from all three tables before sorting:

    SELECT * FROM table1
    UNION ALL
    SELECT * FROM table2
    UNION ALL
    SELECT * FROM table3
    ORDER BY "date" DESC
    LIMIT 100
    

    Note that the above will only work if all tables have the same structure. If you have fields that occur in one table but not in others then you should omit them from the SELECT or else return NULL for that column in the other tables. For example if:

    • table1 has columns a, b, c and date.
    • table2 has columns b, c and date.
    • table3 has columns a, c and date.

    Then use this:

    SELECT a, b, c, "date"
    FROM table1
    UNION ALL
    SELECT NULL AS a, b, c, "date"
    FROM table2
    UNION ALL
    SELECT a, NULL as b, c, "date"
    FROM table3
    ORDER BY "date" DESC
    LIMIT 100
    

提交回复
热议问题