我有一个MySql SELECT查询,它使用了大约6个表,在所有2个表中有超过4000个记录,我使用的查询是:
SELECT DISTINCT r.*,
p.name AS product,
p.price,
p.tax,
l.name AS license_status,
CONCAT(c.firstname, ' ', c.lastname) AS customer,
CONCAT(cc.firstname, ' ', cc.lastname) AS license_customer,
cc.telephone AS license_customer_mobile
FROM order_license r
LEFT JOIN customer c ON (c.customer_id = r.customer_id)
LEFT JOIN order_product p ON (p.order_id = r.order_id
AND r.product_id = p.product_id)
LEFT JOIN license_status l ON (l.license_status_id = r.license_status_id)
LEFT JOIN customer cc ON (cc.customer_id = r.license_customer_id)
WHERE r.license_status_id = '7'
AND r.validity > 0
ORDER BY r.end_date ASC LIMIT 0,10
问题是它需要大约1分钟才能显示记录,这对于如此少的记录来说非常高。 MySql服务器是一个相当快的Linode VPS。现在我不知道什么是错的。
我尝试添加索引并删除LEFT JOINS(如下面的查询中所示),但结果几乎相同。
SELECT r.*,
p.name AS product,
p.price,
p.tax,
l.name AS license_status,
CONCAT(c.firstname, ' ', c.lastname) AS customer,
CONCAT(cc.firstname, ' ', cc.lastname) AS license_customer,
cc.telephone AS license_customer_mobile
FROM order_license r,
order_product p,
license_status l,
customer c,
customer cc
WHERE (p.order_id = r.order_id
AND r.product_id = p.product_id)
AND (l.license_status_id = r.license_status_id)
AND (c.customer_id = r.customer_id)
AND (cc.customer_id = r.license_customer_id)
AND r.license_status_id = '7'
AND r.validity > 0
ORDER BY r.end_date ASC LIMIT 0,10
请帮忙。
答案 0 :(得分:0)
您正在覆盖ON
条款中的WHERE
条件。
改变:
WHERE (p.order_id = r.order_id
AND r.product_id = p.product_id)
AND (l.license_status_id = r.license_status_id)
AND (cc.customer_id = r.license_customer_id)
AND r.license_status_id = '7'
AND r.validity > 0
ORDER BY r.end_date ASC LIMIT 0,10
到
WHERE r.license_status_id = '7'
AND r.validity > 0
ORDER BY r.end_date ASC LIMIT 0,10
答案 1 :(得分:0)
SELECT
R.*,
P.name AS product,
P.price,
P.tax,
L.name AS license_status,
CONCAT( C.firstname, ' ', C.lastname) AS customer
CONCAT( CC.firstname, ' ', CC.lastname) AS license_customer
CC.telephone AS license_customer_mobile
FROM order_license R
LEFT JOIN customer C
ON C.customer_id = R.customer_id
LEFT JOIN order_product P
ON P.order_id = R.order_id
AND P.product_id = R.product_id
LEFT JOIN license_status L
ON L.license_status_id = R.license_status_id
LEFT JOIN customer CC
ON CC.customer_id = R.customer_id
WHERE R.validity > 0
AND R.license_status_id = 7
GROUP BY R.order_license_id
ORDER BY R.end_date LIMIT 10