0

我有以下查询:

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 并执行此查询并将结果写入数据库吗?或者,还有更好的方法?

或者我可以优化这个查询,让它更快?

4

3 回答 3

2

我认为所有那些相关的子查询都在杀死你。尝试这个:

SELECT  p2c.pid AS productNumber,
        p.name AS productName,
        COUNT(*) AS registered,
        SUM(date_add(from_unixtime(purchased), INTERVAL 5 YEAR) >= CURDATE()) AS inWarranty,
        SUM(date_add(from_unixtime(purchased), INTERVAL 5 YEAR) < CURDATE()) AS outOfWarranty,
        DATE_FORMAT( MAX( from_unixtime(purchased) ), '%d.%m.%Y') AS lastPurchased,
        DATE_FORMAT( date_add( MAX( from_unixtime(purchased) ), INTERVAL 5 YEAR), '%d.%m.%Y') AS warrantyUntil
FROM products2customers p2c
JOIN products p ON p.id = p2c.pid
GROUP BY p2c.pid
ORDER BY inWarranty DESC
于 2013-10-25T07:03:04.727 回答
1

也许可以先做一个Explain Plan看看是否有任何部分可以通过创建索引来加速。

于 2013-10-25T06:53:52.233 回答
1

将其放入 cron 作业中:

CREATE TABLE products_warrany SELECT p2c.pid AS productNumber, ...

稍后使用以下查询代替原来的长查询:

SELECT * FROM products_warrany ORDER BY ...

您还可以获得运行额外过滤、排序等的能力。参考。

于 2013-10-25T06:56:07.400 回答