2011-01-08 70 views
0

我從兩個不同的表中選擇數據,它們有一個共同的字段「日期」,我想按日期desc訂購,但我不能得到它的工作,我還沒有找到多少幫助谷歌關於它。如何訂購一個mysql選擇

SELECT table1.id, table1.date, table2.id, table2.date FROM table1, table2 ORDER BY 

此外,我將不勝感激的任何鏈接閱讀更多有關這些類型的查詢,它會救我脫離不必問這裏尋求幫助所有的時間:d感謝。

回答

2

除非你想有一個全面的笛卡爾乘積(你在表1 每結合排在表2),你需要一個限制where子句,如:

select a.id, b.id, b.date 
from  table1 a, table2 b 
where  a.date = b.date 
order by b.date desc 

上述select中的where子句只會合併日期相同的兩個表中的行,這就是您所需要的。

相反,如果你想從兩個不同的表的ID和日期排序日期,你可能需要的東西,如:

select  id, date 
from  table1 
union all 
select  id, date 
from  table2 
order by 2 desc 

這將返回兩個表中的ID和日期,聯合在一起一起,然後使用列號而不是名稱進行排序。

+0

一個完整的笛卡爾積正是我得到的結果 – andrei

+0

@andrei:那麼它聽起來像限制'where'子句是你所需要的。如果日期是某種唯一鍵,那麼每個日期只會返回一行(假設日期在兩個表中)。 – paxdiablo

+0

日期是unix時間戳(不太可能有任何重複),我現在試試看看我得到了什麼 – andrei

2

喜歡的東西:

SELECT table1.id, table1.date, table2.id, table2.date FROM table1, table2 ORDER BY table1.date 

介紹到SQL ORDER BY可以在這裏找到:http://www.w3schools.com/sql/sql_orderby.asp

+0

,但我想兼顧日期,則從兩個表 – andrei

+0

@andrei:你的意思是'的date'領域在paxdiablo的答案中選擇它們時,「table1」和「table2」應該是相同的嗎?或者按大/小排序? –

+0

我想排序的結果以相同的方式,在一個普通的查詢,我有來自table1和table2的數據,並使用它們的公共字段日期,我希望整個束排序desc(意味着行可能混入了eachother) //在我的數據庫中使用where a.date = b.date返回一個空行 – andrei

0
SELECT table1.id, table1.date, table2.id, table2.date FROM table1, table2 ORDER BY table2.date DESC 

,如果你想通過表2的日期訂購

OR

SELECT table1.id, table1.date, table2.id, table2.date FROM table1, table2 ORDER BY table1.date DESC 
0

你可以使用UNION ALL表查詢,像這樣結合:

 
SELECT * FROM 
(
    SELECT 1 AS id, date FROM table1 
    UNION ALL 
    SELECT 2 AS id, date FROM table2 
) T1 
ORDER BY date