1 回答
TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
查看您的代碼,您可以重構(gòu)查詢,避免為每一行選擇一個(gè)子查詢,并在連接中使用兩個(gè)帶有 group by 的子查詢。
您對(duì)壞票和好票也有相同的代碼可能是您需要不同的代碼來獲得不同的值
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
并且您應(yīng)該避免在 SQL 中使用 PHP var(您有 SQL 注入的風(fēng)險(xiǎn))。為此,您應(yīng)該查看您的數(shù)據(jù)庫驅(qū)動(dòng)程序以獲取準(zhǔn)備好的語句和綁定值,或者至少確保您正確清理了 php var 內(nèi)容
- 1 回答
- 0 關(guān)注
- 166 瀏覽
添加回答
舉報(bào)
