最大限度地减少MySQL查询的冗余

时间:2016-10-18 19:15:13

标签: mysql

我在尝试减少MySQL中的查询冗余方面遇到了一些麻烦。我目前有它工作,但感觉我有太多的开销,因为它使用冗余子查询。我想要做的是使用DVD租赁数据库找出哪个商店位置在2005年每月租出更多的DVD。

这是工作查询

SELECT b.month, c.store_id, b.maxRentals
FROM
    (SELECT a.month, MAX(a.rentalCount) as maxRentals
    FROM
        (SELECT MONTH(rental.rental_date) as month, inventory.store_id, count(1) as rentalCount
        FROM rental

        INNER JOIN inventory
        ON rental.inventory_id = inventory.inventory_id

        WHERE YEAR(rental.rental_date) = 2005

        GROUP BY MONTH(rental.rental_date), inventory.store_id
        ) a
    GROUP BY a.month
    ) b

    INNER JOIN

    (SELECT MONTH(rental.rental_date) as month, inventory.store_id, count(1) as rentalCount
    FROM rental

    INNER JOIN inventory
    ON rental.inventory_id = inventory.inventory_id

    WHERE YEAR(rental.rental_date) = 2005

    GROUP BY MONTH(rental.rental_date), inventory.store_id
    ) c
ON b.maxRentals = c.rentalCount

GROUP BY b.month;

注意别名为“c”的子查询是如何与别名“a”完全相同的子查询。我不确定是否有办法摆脱这种情况,因为我无法加入别名。我只是坚持一个巨大的查询,还是我还能做些什么呢?

1 个答案:

答案 0 :(得分:1)

我90%确定此查询会实现您的意图:

SELECT MONTH(r.rental_date), i.store_id, COUNT(*)
FROM rental r
LEFT JOIN inventory i ON r.inventory_id = i.inventory_id
WHERE YEAR(r.rental_date) = 2005
GROUP BY MONTH(r.rental_date), i.store_id

让我知道它是怎么回事!

编辑:回答哪个商店位置在2005年每月租借了更多dvd的问题

SELECT x.rental_month, x.store_id, MAX(x.rental_count) FROM (
SELECT MONTH(r.rental_date) AS rental_month, i.store_id AS store_id, COUNT(*) AS rental_count
FROM rental r LEFT JOIN inventory i ON r.inventory_id = i.inventory_id
WHERE YEAR(r.rental_date) = 2005
GROUP BY MONTH(r.rental_date), i.store_id) x
GROUP BY x.rental_month, x.store_id

我在任何地方使用别名都是明确的,你可以省略一些。希望这有助于......

编辑:肮脏的黑客:

SELECT x.rental_month, x.store_id, MAX(x.rental_count) FROM (
SELECT MONTH(r.rental_date) AS rental_month, i.store_id AS store_id, COUNT(*) AS rental_count
FROM rental r LEFT JOIN inventory i ON r.inventory_id = i.inventory_id
WHERE YEAR(r.rental_date) = 2005
GROUP BY MONTH(r.rental_date), i.store_id
ORDER BY MONTH(r.rental_date) ASC, COUNT(*) DESC) x
GROUP BY x.rental_month

价: http://kristiannielsen.livejournal.com/6745.html

但是,这会让你满意,因为你已经有了一个有效的查询......