MySQL Select - 将COUNT与GROUP_CONCAT结合使用

时间:2009-07-31 06:03:25

标签: php mysql select

我目前有一个MySQL SELECT语句,它从两个表中提取信息,以显示私人消息的“已发送消息”字段。

我想知道如何在查询中添加COUNT来计算一个帖子中“接收者”的数量。

这是我的表结构的基本要点,(注意:两个表之间的关系关系是pm-info中的'message-id'和pm_data中的“id”):

pm_info:
   id     message_id    receiver_id    is_read     read_date

pm_data:
   id    date_sent    title    sender_id    thread_id    content

这是我的SELECT语句:

SELECT pm_info.is_read, group_concat(DISTINCT receiver.usrFirst) as receiver_name,
pm_data.date_sent, pm_data.title, pm_data.thread_id, pm_data.id as data_id,
MAX(date_sent) AS thread_max_date_sent
FROM pm_info
INNER JOIN pm_data ON pm_info.message_id = pm_data.id
INNER JOIN tblUsers AS receiver ON pm_info.receiver_id = receiver.usrID
WHERE pm_data.sender_id = '$usrID'
GROUP BY pm_data.thread_id
ORDER BY thread_max_date_sent DESC

它会像这样输出收件人:

Message 1 - Recipients: John, David, Steve - thread_id = 1234
Message 2 - Recipients: Bill, David, John, Ed, Steve - thread_id = 1345

基本上,我想要做的是选择COUNT收件人,所以在上面的示例中,“Message 1”将显示三(3)个收件人,而“Message 2”将显示五(5)个收件人。

这样,如果我有一个发送给30个用户的帖子/消息,则不会打印出所有30个名字。

谢谢!

3 个答案:

答案 0 :(得分:2)

您是否尝试过使用COUNT替换GROUP_CONCAT?像这样:

COUNT(DISTINCT receiver.usrFirst) as receiver_count

或者更好的是,使用pm_info.receiver_id(这可能会让你消除一个连接):

COUNT(DISTINCT pm_info.receiver_id) as receiver_count

答案 1 :(得分:0)

您可以使用子查询为每条消息选择最多3个收件人,然后使用另一个子查询来连接其名称:

select 
    (   select group_concat(usrFirst separator ', ') 
        from tblUsers
        where usrId in (
            select usrId
            from tblUsers
            where usrId = pm_info.receiver_id
            limit 3
        )
    ) as receiver_name
 from pm_info
 ....

答案 2 :(得分:0)

您可以将count和group_concat移动到concat语句中。

... group_concat(DISTINCT receiver.usrFirst) as receiver_name ...

变为

... concat('messages:', count(distinct receiver.usrFirst),'(',group_concat(DISTINCT receiver.usrFirst),')') as receiver_name ...