我在MySQL中有2个表,在这两个表中我有id,title,date和其他一些字段,一个表的名称是news
,另一个表是gallery
。
Table news :
id | title | date | ...
------+----------+--------------+-------
1 | TestN 1 | 2012-12-12 | ...
2 | TestN 2 | 2012-12-14 | ...
3 | TestN 3 | 2012-12-14 | ...
Table gallery :
id | title | date | ...
------+----------+--------------+-------
1 | TestG 1 | 2012-12-10 | ...
2 | TestG 2 | 2012-12-12 | ...
3 | TestG 3 | 2012-12-15 | ...
我想知道如何按日期顺序从两个表中选择ID,标题记录?有可能吗?
像这样:
Result :
id | title | date | ...
------+----------+--------------+-------
1 | TestG 1 | 2012-12-10 | ...
1 | TestN 1 | 2012-12-12 | ...
2 | TestG 2 | 2012-12-12 | ...
2 | TestN 2 | 2012-12-14 | ...
3 | TestN 3 | 2012-12-14 | ...
3 | TestG 3 | 2012-12-15 | ...
答案 0 :(得分:4)
使用UNION
SELECT id, title, date FROM news
UNION ALL
SELECT id, title, date FROM gallery
ORDER BY date, id, title
答案 1 :(得分:0)
要实现这一点,请使用像这样的UNION子句....
SELECT id,title,date FROM news
UNION
SELECT id,title,date FROM gallery
答案 2 :(得分:0)
您可以使用以下查询
SELECT id,title,date FROM news
UNION All
SELECT id,title,date FROM gallery
ORDER BY date, id, title