简体   繁体   English

MySql按日期对2个或更多表进行排序

[英]MySql Sorting columns from 2 or more tables by date

I have the following tables: 我有以下表格:

comments:
id   /   comments    /   date
1        comment1     1389986953
2        comment2     1389986935


topics:
id   /   topics    /   date
1        topic1      1389986930
2        topic2      1389986940

How can i select all the rows from both tables and sort them by the date? 如何从两个表中选择所有行并按日期对它们进行排序? so it will look something like: 因此它看起来像:

topic1
comment2
topic2
comment1

Try a SELECT UNION 尝试一个SELECT UNION

Reference: http://dev.mysql.com/doc/refman/5.0/en/union.html 参考: http : //dev.mysql.com/doc/refman/5.0/en/union.html

(SELECT comments AS col, date FROM comments)
UNION
(SELECT topics AS col, date FROM topics)
ORDER BY date;

You will want to use UNION ALL to combine the results of both tables, then wrap this to sort. 您将要使用UNION ALL合并两个表的结果,然后将其包装以进行排序。

SELECT a.type 
FROM   (SELECT comments AS type, 
               date 
        FROM   comments 
        UNION ALL 
        SELECT topics, 
               date 
        FROM   topics) a 
ORDER  BY a.date; 
SELECT * FROM
    (SELECT comments AS mergedField, date
    FROM comments
    UNION ALL
    SELECT topics, date
    FROM topics) mergeTable
ORDER BY date ASC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM