gpt4 book ai didi

mysql - 最小化 MySQL 查询的冗余

转载 作者:行者123 更新时间:2023-11-28 23:24:12 24 4
gpt4 key购买 nike

我在尝试减少 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”的子查询完全相同。我不确定是否有办法摆脱这种情况,因为我无法在内部加入别名。我只是被一个巨大的查询困住了,还是我还能做些什么?

最佳答案

我 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

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

关于mysql - 最小化 MySQL 查询的冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40116273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com