我做了一个声明,将返回一个字符串的数据显示用户收件箱只需输入他们的 user_id
.
我有三个表:用户、对话和消息。我正在尝试生成一个sql语句,它将返回 conv_id
, user_id
,name(来自users表),以及在该对话中发送的最后一条消息。到目前为止,我得出的结论是:
SELECT DISTINCT n.conversation AS conv_id, n.user_id, n.name, n.message_body FROM
(SELECT CONCAT(u.first, " ", u.last) AS name, c.conv_id AS conversation, c.user_id, m.message_body
FROM users AS u,
(SELECT conv_id, CASE
WHEN user1="14" THEN user2
WHEN user2="14" THEN user1
END AS user_id FROM conversations) AS c,
(SELECT DISTINCT x.id, x.message_body, x.conv_id FROM messages AS x,
(SELECT conv_id AS convs FROM conversations WHERE user1="14" or user2="14") AS y
WHERE (x.message_from="14" or x.message_to="14") AND x.conv_id=y.convs
ORDER by x.id DESC) AS m
WHERE u.user_id=c.user_id) as n
GROUP BY n.conversation
现在它返回 conversation
, user_id
,和 name
我在寻找,但它给了我错误的 message_body
每次谈话。
我的table是这样的:
用户
user_id | first | last
14 John Smith
15 Steve Lowe
16 Will Willis
对话
conv_id | user1 | user2
4 14 15
5 15 16
6 16 14
信息
id | conv_id | message_to | message_from | message_body
1 4 15 14 alpha
2 4 14 15 beta
3 4 15 14 charlie
4 4 14 15 delta
5 5 16 15 epsilon
6 5 15 16 foxtrot
7 5 16 15 golf
8 5 15 16 hotel
9 6 14 16 india
10 6 16 14 juliette
11 6 14 16 kilo
12 6 16 14 lima
为了 user_id
=14我希望我的语句返回:
conv_id | user_id | name | message_body
4 15 Steve Lowe delta
6 16 Will Willis lima
这是一个很难理解的问题。也许我需要尝试使用连接。
请帮帮我!
sqlfiddle:http://sqlfiddle.com/#!9/70359d号
1条答案
按热度按时间9avjhtql1#
这是一个正在为我工作