Skip to content

Commit 395c614

Browse files
committed
Fixed conversations sql query
1 parent a614fd0 commit 395c614

File tree

1 file changed

+17
-25
lines changed

1 file changed

+17
-25
lines changed

backend/PyMatcha/models/user.py

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -423,31 +423,23 @@ def get_conversation_list(self) -> List[Message]:
423423
with self.db.cursor() as c:
424424
c.execute(
425425
"""
426-
SELECT * FROM messages
427-
JOIN
428-
(
429-
SELECT user, max(timestamp) m
430-
FROM
431-
(
432-
(
433-
SELECT id, to_id user, timestamp
434-
FROM messages
435-
WHERE from_id={0}
436-
)
437-
UNION
438-
(
439-
SELECT id, from_id user, timestamp
440-
FROM messages
441-
WHERE to_id={0}
442-
)
443-
) t1
444-
GROUP BY user
445-
) t2
446-
ON
447-
((from_id={0} AND to_id=user) OR
448-
(from_id=user AND to_id={0})) AND
449-
(timestamp = m)
450-
ORDER BY timestamp DESC
426+
SELECT t1.*
427+
FROM messages AS t1
428+
INNER JOIN
429+
(
430+
SELECT
431+
LEAST(from_id, to_id) AS from_id,
432+
GREATEST(from_id, to_id) AS to_id,
433+
MAX(id) AS max_id
434+
FROM messages
435+
GROUP BY
436+
LEAST(from_id, to_id),
437+
GREATEST(from_id, to_id)
438+
) AS t2
439+
ON LEAST(t1.from_id, t1.to_id) = t2.from_id AND
440+
GREATEST(t1.from_id, t1.to_id) = t2.to_id AND
441+
t1.id = t2.max_id
442+
WHERE t1.from_id = {0} OR t1.to_id = {0}
451443
""".format(
452444
self.id
453445
)

0 commit comments

Comments
 (0)