How do I combine the results of two queries with ordering?

前端 未结 2 1704
走了就别回头了
走了就别回头了 2020-12-15 07:11

How do you join the results of 2 queries, ordering by date?

SELECT * FROM table1 WHERE tag=\'1\'
SELECT * FROM table2 WHERE tag=\'3\'

table

2条回答
  •  春和景丽
    2020-12-15 07:28

    You can use UNION ALL to get rows from both tables:

    SELECT id, article, author, tag, date FROM table1 WHERE tag = '1'
    UNION ALL
    SELECT id, article, author, tag, date FROM table2 WHERE tag = '3'
    ORDER BY date
    

    You may also want to consider restructuring your database so that instead of using two tables you use just a single table with a field to distinguish the type of each row. Then the query can simplify to:

    SELECT id, article, author, tag, date
    FROM yourtable
    WHERE (tag, type) IN (('1','type1'), ('3','type2'))
    ORDER BY date
    

提交回复
热议问题