我正试图了解如何根据HAVING计算mysql行数。
SELECT COUNT(*),
SUM(CASE WHEN sentby='$user_id' AND hiddenbysentby=0 THEN 1 ELSE 0 END) as sentbyuser,
SUM(CASE WHEN sentto='$user_id' AND hiddenbysentto=0 THEN 1 ELSE 0 END) as senttouser
FROM cb_users.user_pm
WHERE title LIKE '%$search%'
HAVING senttouser = 1 OR sentbyuser = 1
我要计算符合这些条件的行
SUM(CASE WHEN sentby='$user_id' AND hiddenbysentby=0 THEN 1 ELSE 0 END)
SUM(CASE WHEN sentto='$user_id' AND hiddenbysentto=0 THEN 1 ELSE 0 END)
我有第二个功能,可以不使用COUNT(*)显示此数据,并且可以正常工作。
但是此查询选择所有行,无论hiddenbysentby = 1或0 AND hiddenbysentto = 1还是0
答案 0 :(得分:0)
您应该通过WHERE子句中的hiddenbysentby和hiddenbysentto字段移动条件,并通过用户ID添加条件
SELECT COUNT(*),
SUM(CASE WHEN sentby='$user_id' THEN 1 ELSE 0 END) as sentbyuser,
SUM(CASE WHEN sentto='$user_id' THEN 1 ELSE 0 END) as senttouser
FROM cb_users.user_pm
WHERE title LIKE '%$search%' AND (hiddenbysentby=0 AND sentby='$user_id') OR (hiddenbysentto=0 AND sentto='$user_id')
HAVING senttouser = 1 OR sentbyuser = 1
答案 1 :(得分:0)
您应将HAVING子句更改为:
具有已发送给用户> = 1或已由发送用户> = 1
在对行求和时,您的值将等于每个行的总行数,因此,除非只有正好符合条件的一行,否则您将找不到想要的结果