我目前有两个几乎相同的SQL查询,我用它来对付我的SQLITE3数据库。
查找匹配记录的总数。
SELECT COUNT(runner.id)
FROM entry
JOIN runner ON runner.entry_id = entry.id
JOIN race ON race.id = entry.race_id
JOIN horse ON horse.id = entry.horse_id
WHERE STRFTIME('%Y-%m-%d', race.datetime) < :max_date AND
STRFTIME('%Y-%m-%d', race.datetime) >= :min_date AND
entry.trainer_id = :trainer_id AND
race.course_id = :course_id AND
race.type = :race_type
查找匹配记录的总数,其中x = y。
SELECT COUNT(runner.id)
FROM entry
JOIN runner ON runner.entry_id = entry.id
JOIN race ON race.id = entry.race_id
JOIN horse ON horse.id = entry.horse_id
WHERE STRFTIME('%Y-%m-%d', race.datetime) < :max_date AND
STRFTIME('%Y-%m-%d', race.datetime) >= :min_date AND
entry.trainer_id = :trainer_id AND
race.course_id = :course_id AND
runner.position = 1 AND
race.type = :race_type
然后我计算PHP代码中x = y记录的百分比。如何从单个SQL查询中返回一个百分比?
编辑:关于优化,我刚刚将WHERE条件转换为更合理的顺序,并添加了一些索引,它从17秒下降到0.1秒。
答案 0 :(得分:1)
运行您的第一个查询并将选择更改为:
SUM(CASE WHEN runner.position = 1 THEN 1 ELSE 0 END) as position1Count, COUNT(runner.id) as total
然后将postionCount除以PHP中的总数。