复杂的MySQL搜索查询

时间:2012-01-29 17:04:36

标签: mysql sql

我在我的userschats表上运行以下查询以加入,我正在group by表{for} chatsuser_id OR receiver_id只需user_id,就像您在INNER JOIN内的SQL查询中看到的那样。

SELECT c.*, users.username, users.firstname, users.lastname 
FROM chats c 
INNER JOIN( SELECT MAX(created) AS Date, user_id, receiver_id, chat, type, id 
FROM chats 
WHERE receiver_id = 286 OR user_id = 286 
GROUP BY user_id ) cc ON cc.Date = c.created AND cc.user_id = c.user_id 
LEFT JOIN users ON users.id = c.user_id 
WHERE c.receiver_id = 286 OR c.user_id = 286

我尝试了GROUP BY user_id OR receiver_id,但我似乎无法获取有关receiver_id或user_id的id 286的信息。

我们有没有办法实现它并分组,以便我们可以查看两个列并从中得出结果?

我是否需要进行两次查询并将它们连接在一起?

1 个答案:

答案 0 :(得分:1)

如果您正在寻找最新的聊天记录,为什么不按创建的方式对结果进行排序,并获得第一行:

SELECT c.*, users.username, users.firstname, users.lastname 
FROM chats c, users u
WHERE (c.receiver_id = 286 OR c.user_id = 286) AND
      u.id = c.user_id 
ORDER BY created DESC
LIMIT 1