我有两张表:附件和订单。
[accessories.category] 包含一个类别列表,即 Red、Green、Blue ... orders 表包含过去订单的列表。
我要选择:
10 records from [accessories.category] WHERE category = 'Red' AND
10 records from [accessories.category] WHERE category = 'Green' AND
10 records from [accessories.category] WHERE category = 'Blue'
我还想引用连接 [accessories.catno] 的订单表,它等于 [orders.catno],仅显示 [accessories.stocklevel] >0 的产品,并按 COUNT(orders.sold) DESC 订购记录集(显示畅销商品第一的)。
因为我想从每个类别中获取一组记录,所以我认为 UNION ALL 查询是合适的,而且确实有效。问题是投入生产的速度不够快,因为在我的开发盒上执行需要 0.3 秒。如果我删除“ORDER BY sold DESC”,查询只需 0.0236 秒,这是可以接受的。问题是我不能丢失 ORDER BY。
顺便说一句:我已经索引了我需要的所有字段。这是查询:
(SELECT
accessories.catno,
accessories.category,
accessories.header,
accessories.description,
accessories.specialoffer,
accessories.picture,
accessories.unit,
accessories.addinfo,
accessories.post,
accessories.price,
accessories.vat,
accessories.soundclip,
COUNT(orders.catno) AS sold
FROM
accessories, orders
WHERE
orders.catno = accessories.catno
AND
accessories.category = 'Red'
AND accessories.stocklevel > 0 AND
accessories.category = 'Red'
GROUP BY catno
ORDER BY sold DESC
LIMIT 10)
UNION ALL
(SELECT
accessories.catno,
accessories.category,
accessories.header,
accessories.description,
accessories.specialoffer,
accessories.picture,
accessories.unit,
accessories.addinfo,
accessories.post,
accessories.price,
accessories.vat,
accessories.soundclip,
COUNT(orders.catno) AS sold
FROM
accessories, orders
WHERE
orders.catno = accessories.catno
AND
accessories.category = 'Green'
AND accessories.stocklevel > 0 AND
accessories.category = 'Green'
GROUP BY catno
ORDER BY sold DESC
LIMIT 10)
UNION ALL
(SELECT
accessories.catno,
accessories.category,
accessories.header,
accessories.description,
accessories.specialoffer,
accessories.picture,
accessories.unit,
accessories.addinfo,
accessories.post,
accessories.price,
accessories.vat,
accessories.soundclip,
COUNT(orders.catno) AS sold
FROM
accessories, orders
WHERE
orders.catno = accessories.catno
AND
accessories.category = 'Blue'
AND accessories.stocklevel > 0 AND
accessories.category = 'Blue'
GROUP BY catno
ORDER BY sold DESC
LIMIT 10)
不确定我是否在此查询中要求太多,或者是否需要重新考虑。有任何想法吗?
添加了 EXPLAIN 的输出。