我在数据库中使用了两个表:
“成员”表:
id | name
-----------------------
1 | John
2 | Mike
3 | Jane
4 | Marry
“消息”表:
message_id | text | from | to
---------------------------------------------
1 | text 1 | 1 | 2
2 | text 2 | 1 | 3
3 | text 3 | 1 | 4
4 | text 4 | 2 | 1
5 | text 5 | 1 | 2
我需要得到特定用户发送的分组消息,按发送的最后一条消息排序,并计算发送给特定用户的消息总数。
我当前的mysql查询看起来:
SELECT max(messages.message_id) as max_mess, messages.from, messages.to, members.name, messages.text
FROM messages INNER JOIN members on members.id = messages.to
WHERE messages.from = '1'
GROUP BY messages.from
ORDER BY max_mess DESC
所需结果应如下所示:
max_mess | from | to | name | text | total_messages
--------------------------------------------------------------------
5 | 1 | 2 | Mike | text 5 | 3
3 | 1 | 4 | Marry | text 3 | 1
2 | 1 | 3 | Jane | text 2 | 1
是否可以仅使用一个mysql查询以及当前查询中应该更改哪些内容?
答案 0 :(得分:1)
您可以使用以下解决方案之一:
解决方案#1(使用额外的JOIN
):
SELECT
m1.max_mess,
m1.from,
m1.to,
m1.name,
m2.text,
m1.total_messages
FROM (
SELECT
MAX(message_id) AS max_mess,
messages.from,
messages.to,
members.name,
COUNT(message_id) AS total_messages
FROM messages INNER JOIN members ON members.id = messages.to
WHERE messages.from = 1
GROUP BY messages.from, messages.to
) m1 LEFT JOIN messages m2 ON m1.max_mess = m2.message_id
ORDER BY m1.max_mess DESC;
注意:此解决方案应该比第二个解决方案更快。您可以在StackOverflow上找到有关以下答案的更多详细信息:JOIN vs. Sub-Query。
解决方案#2(使用子选择):
SELECT
MAX(message_id) AS max_mess,
m1.from,
m1.to,
members.name,
(SELECT messages.text FROM messages WHERE message_id = MAX(m1.message_id)) as text,
COUNT(message_id) AS total_messages
FROM messages m1 INNER JOIN members ON members.id = m1.to
WHERE m1.from = 1
GROUP BY m1.from, m1.to
ORDER BY max_mess DESC;
答案 1 :(得分:0)
这是一个查询。如果要删除JOIN
语句,则应使用
SELECT max(messages.message_id) as max_mess, messages.from, messages.to, members.name, messages.text
FROM messages, members
WHERE messages.from = '1' AND members.id = messages.to
GROUP BY messages.from
ORDER BY max_mess DESC
答案 2 :(得分:0)
我认为你正在寻找这个:
SELECT MAX(messages.message_id) AS max_mess, messages.from, messages.to, members.name, messages.text,, SUM(`from`) total_messages
FROM messages INNER JOIN members ON members.id = messages.to
WHERE messages.from = '1'
GROUP BY messages.from,messages.to
ORDER BY max_mess DESC;