2012-12-16 218 views
4

我在MySQL中有兩個表,在這兩個表中我有id,標題,日期和一些其他字段,一個表的名稱是news,另一個表是gallery從2個表中選擇記錄

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 | ... 

我想知道如何從兩個表中按日期順序選擇標題記錄?可能嗎 ?

像這樣:

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 | ... 

回答

4

使用UNION

SELECT id, title, date FROM news 
UNION ALL 
SELECT id, title, date FROM gallery 
ORDER BY date, id, title 
0

爲了實現這樣的這種使用UNION子句....

SELECT id,title,date FROM news 
UNION 
SELECT id,title,date FROM gallery 
0

您可以使用下面的查詢

SELECT id,title,date FROM news 
UNION All 
SELECT id,title,date FROM gallery 
ORDER BY date, id, title