Heya!,我有以下查询:
SELECT t1.pm_id
FROM fb_user_pms AS t1,
fb_user_pm_replies AS t2
WHERE (t1.pm_id = '{$pm_id}'
AND t1.profile_author = '{$username}'
OR t1.pm_author = '{$username}'
AND t1.pm_id = t2.pm_id
AND t2.pm_author = '{$username}'
AND COUNT(t2.reply_id) > 0)
AND t1.deleted = 0
然而,我收到了一个分组错误 - 我的猜测是由AND COUNT(t2.reply_id)>引起的。 0?
如何纠正上述问题以使其正常工作。
希望有人可以提供帮助。
干杯!
答案 0 :(得分:1)
聚合函数COUNT
不能进入WHERE子句。您应该使用GROUP BY并将其放在HAVING子句中。
SELECT t1.pm_id
FROM fb_user_pms AS t1
JOIN fb_user_pm_replies AS t2 ON t1.pm_id = t2.pm_id
WHERE (
(t1.pm_id = '{$pm_id}' AND t1.profile_author = '{$username}') OR
(t1.pm_author = '{$username}' AND t2.pm_author = '{$username}')
) AND t1.deleted = 0
GROUP BY t1.pm_id
HAVING COUNT(t2.reply_id) > 0
如果t2.reply_id
是NOT NULL列,那么根本不需要HAVING子句。
答案 1 :(得分:0)
答案 2 :(得分:0)
错误是因为您不能在WHERE子句中使用聚合函数(COUNT,MIN,MAX,AVG等),而不在子查询中。只有HAVING
子句允许您使用聚合而不包含在子查询中。
但是在INNER JOIN上检查回复大于零是不必要的 - 这可以保证至少有一个回复与fb_user_pms
记录相关联。 JOIN还意味着t1
中的每个支持的记录都会复制fb_user_pm_replies
中的信息。 IE:如果fb_user_pms
条记录中有三条与此相关的fb_user_pm_replies
条记录,您会在结果集中看到fb_user_pms
条记录三次。
您要使用的查询是:
SELECT t1.pm_id
FROM fb_user_pms AS t1
WHERE t1.pm_id = '{$pm_id}'
AND '{$username}' IN (t1.profile_author, t1.pm_author)
AND t1.deleted = 0
AND EXISTS(SELECT NULL
FROM fb_user_pm_replies AS t2
WHERE t2.pm_id = t1.pm_id
AND t2.pm_author = '{$username}')
EXISTS子句根据WHERE条件返回true或false。它也不会复制t1
结果。