一起使用ORDER BY,GROUP BY和多个SELECT

时间:2014-01-05 21:37:56

标签: mysql

我有两张桌子

TABLE用户

uid  | username 
----------------
1    | brandon   
2    | john   
3    | nicole

TABLE private_msgs

id   | from  | to | message      | time
-------------------------------------------
1    | 1     | 2  | hi sister    | 100
2    | 1     | 3  | hi brother   | 300
3    | 1     | 2  | hi again!    | 400
4    | 2     | 3  | lolz message | 600

(列时间是一个实际的时间戳,我只是简单地说明了这个例子)

'from'是用户的uid

'to'是用户的uid

我想获取发送给特定用户的所有用户的最新消息

本案例中的特定用户是

$logged_id = 2;

结果应该返回id = 3

的行

我到目前为止的查询

SELECT private_msgs.*, users.username FROM `private_msgs`, `users` 
WHERE private_msgs.to=$logged_id AND users.uid = private_msgs.from 
INNER JOIN (
  SELECT 
    from, max(time) as latest 
  FROM private_msgs 
  GROUP BY private_msgs.from
) r ON private_msgs.time = r.latest AND private_msgs.from = r.from
ORDER BY time DESC");

然而,我收到了错误

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN ( SELECT from, max(time) as latest FROM private_msgs ' at line 3

2 个答案:

答案 0 :(得分:0)

查询中有几个错误。除了尾随逗号,fromto是保留字,因此应引用它们:

SELECT pm.*, u.username
FROM `private_msgs` pm join
     `users` u
     on pm.`to` = $logged_id AND u.uid = pm.`from` INNER JOIN
     (SELECT `from`, max(time) as latest 
      FROM private_msgs 
      GROUP BY private_msgs.`from`
     ) r
    ON pm.time = r.latest AND pm.`from` = r.`from`
ORDER BY time DESC;

答案 1 :(得分:0)

在这里,您将收到所有用户的最新消息。这是您的回答者的查询

SELECT * FROM 
    (SELECT * FROM `user` a,` private_msgs` b 
     WHERE a.uid=b.from order by time DESC ) 
      t group by `from`