2013-03-19 59 views
0

這是我的查詢:ORDER BY和LIMIT不工作時使用UNION

mysql_query("SELECT userid FROM messages WHERE userid<>'$myid' AND friendid='$myid' AND status=1 UNION SELECT friendid FROM messages WHERE userid='$myid' AND friendid<>'$myid' AND status=1"); 

我想添加分頁,所以我需要限制的朋友,我的消息的數量。但是每當我添加LIMIT時,它都會顯示錯誤。另外,我想先顯示最新消息ORDER BY time DESC但這不起作用。幫幫我 ?

回答

6

附上一個子查詢和ORDER BY ... LIMIT...內部的查詢外一個:

SELECT * 
FROM 
(
    SELECT userid 
    FROM messages 
    WHERE userid <> '$myid' 
     AND friendid = '$myid' 
     AND status = 1 
    UNION 
    SELECT friendid 
    FROM messages 
    WHERE userid = '$myid' 
     AND friendid <> '$myid' 
     AND status = 1 
) AS sub 
ORDER BY ... 
LIMIT ...; 
+0

一切都很好,除了它顯示:未知列的時間才能條款。我嘗試了'按時間降序排列'和'排序排列子時間降序'呢! – Adil 2013-03-19 15:40:09

+0

@Adil - 沒有選定的名稱爲'time'的列,將其添加到子查詢中:SELECT * FROM(SELECT userid,time FROM ... UNION SELECT friendid,time from ...)AS sub ... ' – 2013-03-19 17:22:01

1

嘗試也許

SELECT DISTINCT userid FROM...