我有一个包含以下列的数据库表:'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
如何只用一个查询计算计数?
答案 0 :(得分:2)
你可以这样做:
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