我有这个查询,很慢。我得到每个选择的计数,并将它们定义为free_cnt
,plus_cnt
列,以便可以在父选择查询中进行操作。
$query = $this->db->query("SELECT movie_title,movie_id,MAX(x.free_cnt) as free_cnt, MAX(x.plus_cnt) as plus_cnt, ((MAX(x.free_cnt)*1) + (MAX(x.plus_cnt)*3)) AS score, (MAX(x.free_cnt) + MAX(x.plus_cnt)) AS total
FROM (
SELECT b.id as movie_id, b.movie_title as movie_title, COUNT(*) AS free_cnt, 0 as plus_cnt
FROM preview_movie_request a1
LEFT JOIN movies b on a1.movie_id=b.id
JOIN users c on c.email=a1.email
WHERE c.subsc_status='0' AND c.package_type='' AND b.movie_type=2 $where1
GROUP BY b.movie_title
UNION ALL
SELECT d.id as movie_id, d.movie_title as movie_title, 0 as free_cnt, COUNT(*) AS plus_cnt
FROM preview_movie_request a2
LEFT JOIN movies d on a2.movie_id=d.id
JOIN users e on e.email=a2.email
WHERE e.subsc_status='1' AND e.package_type!='' AND d.movie_type=2 $where2
GROUP BY d.movie_title
UNION ALL
) AS x
GROUP BY movie_title
$orderby
$limit");
反正有没有简化查询并使其更快?
答案 0 :(得分:1)
您可以消除一个子查询来移动计数条件,以防万一
SELECT movie_title,movie_id,MAX(x.free_cnt) as free_cnt, MAX(x.plus_cnt) as plus_cnt, ((MAX(x.free_cnt)*1) + (MAX(x.plus_cnt)*3)) AS score, (MAX(x.free_cnt) + MAX(x.plus_cnt)) AS total FROM
(
SELECT b.id as movie_id, b.movie_title as movie_title,
SUM(CASE WHEN c.subsc_status='0' AND c.package_type='' AND b.movie_type=2 $where1 THEN 1 END ) AS free_cnt,
SUM(CASE WHEN c.subsc_status='1' AND c.package_type!='' AND b.movie_type=2 $where2 THEN 1 END ) AS plus_cnt,
FROM preview_movie_request a1
LEFT JOIN movies b on a1.movie_id=b.id
JOIN users c on c.email=a1.email
GROUP BY b.movie_title)x
GROUP BY movie_title
$orderby
$limit