我正在尝试使用下面的查询计算特定字段的记录数。
SELECT COUNT(DISTINCT CASE WHEN seen='n' and reciever_id=1 THEN 'varb' ELSE 'novarb' END) AS count ,c.id, c.vmsg, c.sender_id, p.fname, p.lname, p.profile_pix, p.profile_id
FROM chats c LEFT JOIN profile p ON c.sender_id = p.profile_id
WHERE c.reciever_id = 1 AND c.id in (SELECT MAX(c.id) as id FROM chats c
GROUP BY c.sender_id )
但我得到的答案只返回一条记录,而其他数百条显示
答案 0 :(得分:0)
如果您使用varb
和novarb
,如果您有1表示您只有一个条件,那么该数字最多为2
可能需要计算varb
条目的数量
SELECT COUNT(
CASE WHEN seen ='n' and reciever_id=1
THEN 'varb'
ELSE NULL
END) AS count ,c.id, c.vmsg, c.sender_id, p.fname, p.lname, p.profile_pix, p.profile_id
FROM chats c
LEFT JOIN profile p ON c.sender_id = p.profile_id
WHERE c.reciever_id = 1 AND c.id in (
SELECT MAX(c.id) as id FROM chats c
GROUP BY c.sender_id )
答案 1 :(得分:0)
我通常会将SUM()
用于此目的。如果我理解正确,您需要满足条件且不符合条件的行数:
SELECT SUM( seen = 'n' and reciever_id = 1 ) as varb,
SUM( not (seen = 'n' and reciever_id = 1) ) as novarb,
c.id, c.vmsg, c.sender_id, p.fname, p.lname, p.profile_pix, p.profile_id
FROM chats c JOIN -- I doubt a left join is necessary
profile p
ON c.sender_id = p.profile_id
WHERE c.reciever_id = 1 AND
c.id in (SELECT MAX(c2.id) FROM chats c2 GROUP BY c2.sender_id)