gpt4 book ai didi

mysql - 按另一个表列 mysql 排序

转载 作者:可可西里 更新时间:2023-11-01 08:17:42 24 4
gpt4 key购买 nike

我有两个表,messagesthread messages 是主表,而 thread 是我保持两个用户之间对话的地方。我只想从 messages 表中选择并按 thread_idthread 表中排序。我正在使用下面的 sql,但它没有按我想要的那样排序。

我的目标是当新消息插入到thread 表时,使messages 表中的父消息出现在顶部。有人知道吗?

SELECT m.* 
FROM messages AS m
JOIN thread AS t
ON t.thread_id = m.id
WHERE ( m.to_user = ?
AND m.deleted != ?
AND m.del2 != ?)
OR
(m.from_user = ?
AND m.conversation = 'true'
AND m.deleted != ?
AND m.del2 != ?)
ORDER BY t.thread_id desc);

消息表

id      to_user  from_user      message      is_read     deleted     del2   conversation
----------------------------------------------------------------------------------------
1 user1 user2 hi mark, true true
2 user3 user4 wass up yo? true true
3 user1 user3 blah blah

线程表

thread_id      thread_to_user  thread_from_user      thread_message     thread_message_id  thread_is_read
---------------------------------------------------------------------------------------------------

1 user2 user1 hi there, 1 1
2 user1 user2 hey, wassup 1 1
3 user2 user1 not much, hw u doin 1 1
4 user1 user2 doing great and you? 1 0
5 user3 user4 heyyyy 2 1
6 user4 user3 hi, u coming? 2 0

回显该行时我的期望是什么:

id      to_user  from_user      message      is_read     deleted     del2   conversation
----------------------------------------------------------------------------------------
2 user3 user4 wass up yo? true true
1 user1 user2 hi mark, true true
3 user1 user3 blah blah

最佳答案

试试这个:

SELECT DISTINCT(id), to_user,from_user,
message, is_read, conversation
FROM messages
LEFT JOIN (
SELECT thread_id, thread_message_id
FROM messages m
LEFT JOIN thread t
ON m.id = t.thread_message_id
) tbl
ON messages.id = tbl.thread_message_id
ORDER BY tbl.thread_id DESC

参见 fiddle demo

您可以将WHERE 放在子查询中,例如:

 SELECT DISTINCT(id), to_user,from_user,
message, is_read, conversation
FROM messages
LEFT JOIN (
SELECT thread_id, thread_message_id
FROM messages m
LEFT JOIN thread t
ON m.id = t.thread_message_id
WHERE ( m.to_user = ?
AND m.deleted != ?
AND m.del2 != ?)
OR
(m.from_user = ?
AND m.conversation = true
AND m.deleted != ?
AND m.del2 != ?)
) tbl
ON messages.id = tbl.thread_message_id
ORDER BY tbl.thread_id DESC

参见 Fiddle Demo with WHERE

更新(使用 MAX() 子查询)

SELECT id, to_user, from_user, message, is_read, conversation
FROM (
SELECT m.id, max(t.thread_id) thread_id, m.to_user,m.from_user,m.message, m.is_read, m.conversation
FROM messages m
LEFT JOIN thread t on(t.thread_message_id = m.id)
WHERE ( m.to_user = 'user1'
AND m.deleted != true
AND m.del2 != true)
OR
(m.from_user = 'user3'
AND m.conversation = true
AND m.deleted != true
AND m.del2 != true)
GROUP BY m.id
ORDER BY thread_id desc
) tbl

See Other Demo

关于mysql - 按另一个表列 mysql 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20063451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com