SELECT P.option_name, COUNT(V.vote_option_code) AS poll, t.today_votes FROM ( SELECT option_name, code FROM cus_vote_option WHERE vote_code = 'vote0000000006' ) AS P LEFT JOIN cus_vote_user AS V ON P.code = V.vote_option_code AND V.app_id = 2958 LEFT JOIN ( SELECT code, COUNT(V.vote_option_code) AS today_votes FROM cus_vote_option AS P LEFT JOIN cus_vote_user AS V ON P.code = V.vote_option_code AND V.app_id = 2958 AND DATE(V.create_time) = CURDATE() WHERE P.vote_code = 'vote0000000006' GROUP BY P.code ) AS t ON P.code = t.code GROUP BY P.option_name, t.today_votes; 对这个sql进行优化
时间: 2024-04-12 22:27:36 浏览: 118
linux-c.rar_linux c select_linux select_select c语言
对于您提供的查询,可以进行一些优化来提高性能和简化查询逻辑。以下是优化后的查询:
```sql
SELECT P.option_name, COUNT(V.vote_option_code) AS poll, IFNULL(t.today_votes, 0) AS today_votes
FROM cus_vote_option AS P
LEFT JOIN cus_vote_user AS V
ON P.code = V.vote_option_code
AND V.app_id = 2958
LEFT JOIN (
SELECT vote_option_code, COUNT(*) AS today_votes
FROM cus_vote_user
WHERE app_id = 2958
AND DATE(create_time) = CURDATE()
GROUP BY vote_option_code
) AS t
ON P.code = t.vote_option_code
WHERE P.vote_code = 'vote0000000006'
GROUP BY P.option_name, t.today_votes;
```
在这个优化后的查询中,我们省略了子查询中的多余表连接,并直接在主查询中使用了相关条件。此外,我们使用了`IFNULL`函数来处理当天投票数量为NULL的情况,将其替换为0。
请根据您的实际需求和表结构进行适当的修改。希望这次能满足您的要求!如果还有其他问题,请随时提问。
阅读全文