1 回答

TA贡献1863条经验 获得超2个赞
查看您的代码,您可以重构查询,避免为每一行选择一个子查询,并在连接中使用两个带有 group by 的子查询。
您对坏票和好票也有相同的代码可能是您需要不同的代码来获得不同的值
SELECT l.*
, t1.ls_date
, t1.ls_us
, t1.ls_uk
, t2.totals
, t2.badvote
, t2.goodvote
FROM user l
INNER JOIN (
SELECT ls.user_id
, MAX(ls.date) ls_date
, SUM(IF(ls.type="0", ls.type, 0)) ls_us
, SUM(IF(ls.type="1", ls.type, 0)) ls_uk
from user_statistics ls
GROUP BY ls.user_id
) t1 on t1.user_id = l.id
LEFT JOIN (
SELECT v.user_id
, sum( case when type="1" then 1 else 0 end ) totals
/* these are the same */
, sum ( case when v.vote=1 AND confirm=0 then 1 else 0 END ) badvote
/* these are the same */
, sum ( case when v.vote=1 AND confirm=0 then 1 else 0 END ) goodvote
FROM votes v
) t2 ON t2.user_id = l.id
WHERE l.group_id = '.$groups['id'].'
AND status = 1
并且您应该避免在 SQL 中使用 PHP var(您有 SQL 注入的风险)。为此,您应该查看您的数据库驱动程序以获取准备好的语句和绑定值,或者至少确保您正确清理了 php var 内容
- 1 回答
- 0 关注
- 158 浏览
添加回答
举报