yak27
yak27

Reputation: 94

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. 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

$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,
That links to the message_user table which has a sent_id and a receive_id,
The message_user has a message_id that corresponds to the message.id,
The message table has a timestamp.

I would like this to be done in SQL but if it comes down to PHP I resign to resort to that.

Upvotes: 1

Views: 59

Answers (2)

yak27
yak27

Reputation: 94

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.

Upvotes: 1

Andreas
Andreas

Reputation: 2837

Use 2 LEFT JOIN with a DISTINCT (untested):

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;

Upvotes: 0

Related Questions