|
我有以下查询:7 S7 U. d6 F8 W. V
SELECT p2c.pid AS productNumber,7 G* C/ P: h8 [: W' o
p.name AS productName
! `/ z' M9 i% m+ N5 j , (% b. f4 f' @+ W6 W- t
SELECT COUNT(*)" @% j' K$ ]0 R( X: R, V( ?. T& ?
FROM products2customers& j( F5 |: E/ H$ \ c
WHERE pid = p2c.pid2 s' q; T. i, {- H; ?! |8 C$ t" h3 g
) AS registered* M+ S) m; G% z$ f
, (1 R: R! S# _6 q# b2 k
SELECT COUNT(*)* g3 F2 Z2 b" Z: i
FROM products2customers: s( r9 e. Y6 s1 |$ h
WHERE pid = p2c.pid
5 d+ X$ g/ L$ W P" H1 H6 x AND date_add(from_unixtime(purchased), INTERVAL 5 YEAR) >= CURDATE()
7 E o G" s f2 u3 ` ) AS inWarranty- U- d8 W! h/ D1 }
, ($ v# O5 _6 Y! r) I
SELECT COUNT(*)
) S& A4 k( g0 U6 C; c$ Y FROM products2customers+ W0 A; {5 j3 R' e2 [ v u
WHERE pid = p2c.pid
3 \& }6 ]2 K7 w1 b6 p* ?3 z4 r AND date_add(from_unixtime(purchased), INTERVAL 5 YEAR) 查询在具有25.000行的数据库表上执行。该查询的执行时间约为40秒。结果将显示在网页上,因此等待40秒以获取结果并不是很好。
% S% q) c5 E' Y) f- |- c有没有一种方法可以执行此查询并保存其输出?因为如果每天晚上执行此查询就足够了。
! O& P3 ~9 A4 w3 L9 y! ?$ ~最好的方法是什么?我应该创建一个cronjob并执行此查询并将结果写入数据库吗?或者,还有更好的方法?
6 _0 c& r4 Y8 D或者我可以优化此查询以使其更快?
3 n7 K" N: X$ {9 v5 }
2 @6 V' W) H) u+ H9 h B) I5 N解决方案:* d+ T- c1 B9 r, z: u% ]& {
+ ]5 F/ ^- b4 H% I8 {2 P' ?/ W! M$ @, K1 _) r6 m% K9 k9 |
9 q/ g% q* G( l2 O+ b 我认为所有这些相关的子查询都在杀死。试试这个:: d% e0 W4 g0 V+ e' c+ @% S
SELECT p2c.pid AS productNumber,
3 L; X* P' h+ x% | p.name AS productName,9 r& n5 y' Q9 R' o
COUNT(*) AS registered,
4 N6 R7 Z4 f2 y9 a* F3 P) `; U SUM(date_add(from_unixtime(purchased), INTERVAL 5 YEAR) >= CURDATE()) AS inWarranty, i* w9 b& a$ F" ?
SUM(date_add(from_unixtime(purchased), INTERVAL 5 YEAR) < CURDATE()) AS outOfWarranty,
* v9 L2 z; y7 K DATE_FORMAT( MAX( from_unixtime(purchased) ), '%d.%m.%Y') AS lastPurchased,& o. k; q9 }/ z+ \- r
DATE_FORMAT( date_add( MAX( from_unixtime(purchased) ), INTERVAL 5 YEAR), '%d.%m.%Y') AS warrantyUntil7 d2 K) V ~4 _+ d
FROM products2customers p2c) w) [6 I- v- x/ C
JOIN products p ON p.id = p2c.pid
5 J P8 ^4 a: n3 S& RGROUP BY p2c.pid6 f& Z. G: C; z) C6 E
ORDER BY inWarranty DESC |
|