2011-11-02 72 views
1

我得到了我的工會聲明以我想要的方式工作,但我似乎無法得到它訂購2表沒有錯誤。php mysql union order by

$query = mysql_query("SELECT userid_2 FROM messages WHERE userid_1='$dbid' UNION SELECT userid_1 FROM messages WHERE userid_2='$dbid'"); 

我試圖將ORDER BY日期合併到它中,但它似乎不起作用。

感謝

+1

你得到的錯誤是什麼? – Neal

+1

http://stackoverflow.com/questions/7881587/query-is-not-being-sorted-properly/7881698#7881698 –

+0

警告:mysql_num_rows()期望參數1是資源,布爾在/ home/skycityc/public_html中給出/pages/messages.php on line 141 –

回答

0

你嘗試過:

$query = mysql_query(" 
     SELECT * FROM (
     SELECT userid_2,date FROM messages 
     WHERE userid_1='$dbid' 
     UNION 
     SELECT userid_1, date 
     FROM messages 
     WHERE userid_2='$dbid' 
    ) as table1 
ORDER by table1.date"); 

編輯:
根據您的評論如下,我會做這樣的事情:

 SELECT * FROM (
     SELECT userid_1,userid_2 FROM messages 
     WHERE userid_1='$dbid' 
     ORDER BY date ASC) as table1 
     UNION 
     SELECT * FROM (
     SELECT userid_1,userid_2 
     FROM messages 
     WHERE userid_2='$dbid' 
     ORDER BY date ASC) as table2 
+0

ID必須改變這個唯一的事情就是我試圖對它進行排序的字段?那麼table1.date?如果這樣也行不通。同樣的錯誤。 –

+0

是的,我編輯了查詢,你還需要從「內部」查詢中選擇日期......否則你不能按日期排序......現在嘗試......我試着在一個示例表中工作...... – Marcx

+0

已經訂購了它,但現在它不是獨特的。你不能把DISTINCT放在那裏,因爲它應該已經是它了嗎? –