开发者

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

开发者 https://www.devze.com 2023-02-17 12:05 出处:网络
How do you join th开发者_如何学运维e results of 2 queries, ordering by date? SELECT * FROM table1 WHERE tag=\'1\'

How do you join th开发者_如何学运维e results of 2 queries, ordering by date?

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

table1,table2 have the same fields: id|article|author|tag|date

PS: BY THE WAY, tag IS workid


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


SELECT * 
FROM   (SELECT * 
        FROM   table1 
        UNION 
        SELECT * 
        FROM   table2) t 
ORDER  BY t.DATE 
0

精彩评论

暂无评论...
验证码 换一张
取 消