我有一个PHP / MySQL应用程序
应用程序使用查询来获取表leads
的值,并使用2个子查询返回第二个表refunds
中的SUM和COUNT值
这两个表与外键lead_id
SELECT l.*,
IFNULL(
(SELECT SUM(amount)
FROM refunds r
WHERE l.lead_id = r.lead_id),0) amount_refunded,
IFNULL(
(SELECT COUNT(*)
FROM refunds r
WHERE l.lead_id = r.lead_id),0) number_refunded
FROM leads l
我想提高此查询的效果。
我的想法是:
以下示例:
SELECT l.*,
(SELECT CONCAT(IFNULL(COUNT(*),0),'|', IFNULL(SUM(amount),0))
FROM fee_refunds r
WHERE l.lead_id = r.lead_id) values_refunded
FROM fee_leads l
然后在应用程序中,在循环中:
list($amount_refunded, $number_refunded) = explode('|', $row->values_refunded);
这种方法有效,但我的问题是:
答案 0 :(得分:3)
使用join
!
SELECT l.*, r.amount_refunded, r.number_refunded
FROM leads l LEFT JOIN
(SELECT lead_id, COUNT(*) as number_refunded, SUM(amount) as amount_refunded
FROM refunds r
GROUP BY lead_id
) r
ON l.lead_id = r.lead_id;
在某些情况下,您可能会在汇总前发现join
更快。