加入mysql表或使查询运行得更快

时间:2015-05-21 07:09:35

标签: php mysql

我承认在加入数据库表时不是最聪明的,所以需要一些帮助。目前我有2个查询,主要是:

SELECT 
    s.id AS show_id, 
    start_date, 
    end_date
FROM `show` s, `theater_type` tt
WHERE
    s.theater = tt.theater_id AND
    image = 1 AND
    start_date > '2015-05-21' AND
    genre_id IN (1,2,3,12,13,17,21) AND
    tt.type_id IN (1,2,3,4)

这是我需要的过滤和返回节目。到目前为止,这是非常好的,但对于每个节目,我也需要它的平均评级。作为一名伐木工人,我正在循环上面的结果并使用此查询来检索每个show_id的平均值:

SELECT AVG(rating) AS avgr FROM pro_reviews WHERE show_id = X

这也很好,但通常第一个查询返回超过1k的结果,因此整个过程运行超过10秒,这对最终用户来说是不可接受的。

我正在加入查询并一次性完成所有操作。也许这也不会更快,但我没有选择。

这是我尝试过的,显然这是错误的,因为它只返回一行:

SELECT 
    AVG(rating) AS avgr,
    allshows.show_id,
    allshows.start_date,
    allshows.end_date
FROM 
    pro_reviews pr,
    (
        SELECT s.id AS show_id, start_date, end_date
        FROM `show` s, theater_type tt
        WHERE s.theater = tt.theater_id AND image = 1 AND start_date > '2015-05-21' AND genre_id IN (1,2,3,12,13,17,21) AND tt.type_id IN (1,2,3,4)
    ) allshows
WHERE allshows.show_id = pr.show_id

首先解释选择返回

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra   
1   SIMPLE  tt  ALL     NULL    NULL    NULL    NULL    209     Using where
1   SIMPLE  s   ALL     NULL    NULL    NULL    NULL    5678    Using where; Using join buffer

2 个答案:

答案 0 :(得分:0)

  1. 创建视图

    创建视图all_shows AS
    SELECT s.id AS show_id,start_date,end_date

    FROM show s,theater_type tt

    WHERE.theater = tt.theater_id AND image = 1 AND genre_id IN(1,2,3,12,13,17,21)AND tt.type_id IN(1,2,3,4);

  2. 然后使用此视图进行选择

    选择     AVG(pro_reviews.rating)AS avgr,     all_shows.show_id,     all_shows.start_date,     all_shows.end_date

    FROM pro_reviews

    INNER JOIN     all_shows ON(all_shows.show_id = pr.show_id)

    WHERE all_shows.start_date> '2015年5月21日'

    GROUP BY pro_reviews.show_id;

答案 1 :(得分:0)

SELECT
    AVG(pr.rating) AS avgr
    s.id AS show_id, 
    start_date, 
    end_date
FROM `show` s 
JOIN `theater_type` tt
ON s.theater = tt.theater_id
LEFT JOIN `pro_reviews` pr
ON s.id = pr.show_id
WHERE
    image = 1 AND
    start_date > '2015-05-21' AND
    genre_id IN (1,2,3,12,13,17,21) AND
    tt.type_id IN (1,2,3,4)
GROUP BY s.id
相关问题