我有一个包含以下列的数据库表:'dialogue', 'user_id','readed'。我想为每次对话统计未读邮件。

例如:

select count(messageid) from messages where user_id = $id and readed=0 and diyalogid = $diyalog1

select count(messageid) from messages where user_id = $id and readed=0 and diyalogid = $diyalog2

select count(messageid) from messages where user_id = $id and readed=0 and diyalogid = $diyalog3


如何仅通过一个查询来计算计数?

最佳答案

您可以这样做:

SELECT
    SUM(CASE WHEN diyalogid = $diyalog1 THEN 1 ELSE 0 END) AS diyalog1Count,
    SUM(CASE WHEN diyalogid = $diyalog2 THEN 1 ELSE 0 END) AS diyalog2Count,
    SUM(CASE WHEN diyalogid = $diyalog3 THEN 1 ELSE 0 END) AS diyalog3Count
FROM
    messages
WHERE
    user_id = $id
    AND readed=0


编辑

为了回答你的评论。我不太确定你想要什么。您可以这样做:

SELECT
    COUNT(*) AS theCount,
    diyalogid
FROM
    messages
WHERE
    user_id = $id
    AND readed=0
GROUP BY
    diyalogid


然后,每个diyalogid都有一个计数

关于mysql - 我们如何从表中获得多计数值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22088674/

10-10 14:46