[英]Sort mysqli from a many-to-many table
I'm trying to make a internal web based message system, with a *amp system, primarily for learning purposes.我正在尝试使用 *amp 系统制作一个基于网络的内部消息系统,主要用于学习目的。 I don't know if this is a trivial topic, but I'm having difficulties so please bear with me.
我不知道这是否是一个微不足道的话题,但我遇到了困难,所以请耐心等待。
The goal is to list all the contacts ordered by the last message sent / received.目标是列出按发送/接收的最后一条消息排序的所有联系人。 Currently without sorting it the SQL looks like this
目前没有对其进行排序,SQL 看起来像这样
$query = "SELECT username, user.id as user_id,
(SELECT COUNT(message_read)
FROM message_user
WHERE message_read = 0
AND sent_id = user_id
AND receive_id = {$userId}) as unread
FROM user
WHERE user.id IN
(SELECT contact_id FROM allowed_contact WHERE user_id = {$userId})
;";
The structure of the tables are:表的结构是:
The user
table has an id
, user
表有一个id
,
That links to the message_user
table which has a sent_id
and a receive_id
,链接到具有
sent_id
和receive_id
的message_user
表,
The message_user
has a message_id
that corresponds to the message.id
, message_user
有一个message_id
对应于message.id
,
The message
table has a timestamp
. message
表有一个timestamp
。
I would like this to be done in SQL but if it comes down to PHP I resign to resort to that.我希望这可以在 SQL 中完成,但如果归结为 PHP,我就辞职求助于此。
This works.这有效。
SELECT `u`.`id` AS user_id, username,
(SELECT COUNT(message_user.message_read)
FROM message_user
WHERE message_user.message_read = 0
AND sent_id = user_id
AND receive_id = {$userId}) as unread
FROM `user` AS `u`
LEFT JOIN `message_user` AS `mu`
ON
(CASE WHEN `u`.`id` != {$userId}
THEN `u`.`id` = `mu`.`sent_id`
WHEN `mu`.`sent_id` = {$userId} AND `mu`.`receive_id` = {$userId}
THEN `u`.`id` = `mu`.`sent_id`
END)
OR
(CASE WHEN `u`.`id` != {$userId}
THEN `u`.`id` = `mu`.`receive_id`
END)
LEFT JOIN `message` AS `m` ON `m`.`id` = `mu`.`message_id`
WHERE u.id IN
(SELECT contact_id FROM allowed_contact WHERE user_id = {$userId})
GROUP BY u.id
ORDER BY MAX(`m`.`timestamp`) DESC;
This broke down the problem I was having. 这打破了我遇到的问题。
@Andreas thanks for time and help. @Andreas 感谢您的时间和帮助。
Use 2 LEFT JOIN
with a DISTINCT
(untested):使用 2
LEFT JOIN
和DISTINCT
(未经测试):
SELECT DISTINCT `u`.`id`
FROM `user` AS `u`
LEFT JOIN `message_user` AS `mu` ON `u`.`id` = `mu`.`sent_id` OR `u`.`id` = `mu`.`receive_id`
LEFT JOIN `message` AS `m` ON `m`.`id` = `mu`.`message_id`
ORDER BY `m`.`timestamp` DESC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.