我有一个名为messages的数据库表:
Column Type
global_ref_id int(12)
to int(12)
from int(12)
message text
status int(1)
viewed int(1)
其中global_ref_id是消息的id(来自表事件的外键),是接收消息的用户的用户id,来自发送消息的用户的用户ID。
我想生成一个查询,该查询给出了显示每个用户向用户发送最后一条消息的结果(比如说其user_id为192),同时也将每个用户的消息总数提供给用户192.
直到现在我想出了这个查询来获得结果:
> SELECT messages.*
> FROM messages, events
> WHERE events.global_id = messages.global_ref_id
> AND to = 192
> GROUP BY messages.from
> ORDER BY events.event_time DESC
答案 0 :(得分:0)
要更改查询的最小值,请执行以下操作(顺便未经测试):
SELECT * FROM
(
SELECT messages.*,events.event_time, COUNT(messages.from) as "Total Messages Between Users"
FROM messages, events
WHERE events.global_id = messages.global_ref_id
AND messages.to = 192
GROUP BY messages.from
ORDER BY messages.from
)
AS EVENTS
ORDER BY events.event_time
LIMIT 1;
LIMIT 1
只会显示最后一条消息,如果您想要所有消息而不是最后一条消息,请删除。
答案 1 :(得分:0)
结果显示每个用户向用户发送的最后一条消息(例如,其user_id为192)
SELECT
messages.message as 'Last Message'
FROM
messages, events
WHERE
events.global_id = messages.global_ref_id
AND to = 192
GROUP BY messages.from
ORDER BY events.event_time DESC
LIMIT 1
每个用户到用户192的消息总数
SELECT
messages.*, COUNT(messages.from) as "Total number of Messages to User"
FROM
messages, events
WHERE
events.global_id = messages.global_ref_id
AND to = 192
GROUP BY messages.from
ORDER BY events.event_time DESC
答案 2 :(得分:0)
答案 3 :(得分:0)
SELECT
m.global_ref_id,
m.`to`,
m.`from`,
m.message,
m.status,
m.viewed
FROM messages m
WHERE m.global_ref_id = (SELECT max(i.global_ref_id)
FROM messages igroup
WHERE i.`to` = m.`to`
AND i.`from` = m.`from`);
会给你最新消息;获得总数将是另一个查询...
SELECT
m.`to`,
m.`from`,
count(*)
FROM messages m
GROUP BY m.`to`, m.`from`
合并这两个查询的输出是另一个问题!
答案 4 :(得分:0)
最后我想出了答案,我不知道这个查询有多好,但它对我有用: -
SELECT messages.global_ref_id,
messages.`to`,
messages.`from`,
messages.message,
messages.status,
messages.viewed,
events.event_time,
count_table.msg_count as `total Number of messages`
FROM
messages
INNER JOIN
(select max(global_ref_id) as ref_id, count(*) msg_count from messages group by `from`)
as count_table
on (messages.global_ref_id = count_table.ref_id)
INNER JOIN events
on (events.global_id = messages.global_ref_id)
where messages.`to` = 192
order by events.global_id DESC
谢谢大家......