我有以下查询:
SELECT p2c.pid AS productNumber,
p.name AS productName
, (
SELECT COUNT(*)
FROM products2customers
WHERE pid = p2c.pid
) AS registered
, (
SELECT COUNT(*)
FROM products2customers
WHERE pid = p2c.pid
AND date_add(from_unixtime(purchased), INTERVAL 5 YEAR) >= CURDATE()
) AS inWarranty
, (
SELECT COUNT(*)
FROM products2customers
WHERE pid = p2c.pid
AND date_add(from_unixtime(purchased), INTERVAL 5 YEAR) < CURDATE()
) AS outOfWarranty
, (
SELECT DATE_FORMAT( MAX( from_unixtime(purchased) ), '%d.%m.%Y')
FROM products2customers
WHERE pid = p2c.pid
) AS lastPurchased
, (
SELECT DATE_FORMAT( date_add( MAX( from_unixtime(purchased) ), INTERVAL 5 YEAR), '%d.%m.%Y')
FROM products2customers
WHERE pid = p2c.pid
) AS warrantyUntil
FROM (
SELECT DISTINCT
p2c.pid
FROM
products2customers p2c
) AS p2c
JOIN
products p
ON
p.id = p2c.pid
ORDER BY
inWarranty DESC
查询在一个有 25.000 行的数据库表上执行。此查询的执行时间约为 40 秒。结果将显示在网页上,因此等待 40 秒等待结果并不是那么好。
有没有办法执行这个查询并保存它的输出?因为如果这个查询每晚执行就足够了。
这样做的最佳方法是什么?我应该创建一个 cronjob 并执行此查询并将结果写入数据库吗?或者,还有更好的方法?
或者我可以优化这个查询,让它更快?