使用UNION时,ORDER BY和LIMIT不起作用

时间:2013-03-19 11:16:15

标签: mysql sql database 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,但这也不起作用。帮忙?

2 个答案:

答案 0 :(得分: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 ...;

答案 1 :(得分:1)

尝试一下

SELECT DISTINCT userid FROM...