MySQL 如何将两个查询的结果与排序结合起来?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5331808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I combine the results of two queries with ordering?
提问by cj333
How do you join the results of 2 queries, ordering by date?
你如何加入 2 个查询的结果,按日期排序?
SELECT * FROM table1 WHERE tag='1'
SELECT * FROM table2 WHERE tag='3'
table1,table2 have the same fields:
id|article|author|tag|date
table1,table2 具有相同的字段:
id|article|author|tag|date
PS: BY THE WAY, tag IS workid
PS:顺便说一下,标签是 workid
回答by Mark Byers
You can use UNION ALL
to get rows from both tables:
您可以使用UNION ALL
从两个表中获取行:
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
回答by Pentium10
SELECT *
FROM (SELECT *
FROM table1
UNION
SELECT *
FROM table2) t
ORDER BY t.DATE