1

我有这个名为消息的数据库表:

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(来自表事件的外键),to 是接收消息的用户的用户 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
4

5 回答 5

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 
于 2012-11-19T11:59:28.810 回答
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

谢谢大家...

于 2012-11-20T07:07:56.363 回答
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仅显示最后一条消息,如果您想要所有消息而不是最后一条消息,请摆脱。

于 2012-11-19T11:46:56.553 回答
0

我认为这就是您想要的,尽管我只是 MySQL 的新手。

http://sqlfiddle.com/#!2/d0586/8

米。to和米。from因为它们是保留字,所以在反引号中。

希望能帮助到你!

于 2012-11-19T12:56:35.820 回答
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`

合并这两个查询的输出是另一个问题!

于 2012-11-19T14:45:21.283 回答