这是我的代码。
SELECT m.id, (SELECT count(r.id)
FROM reports as r
WHERE r.date BETWEEN NOW()-INTERVAL '7 days' AND NOW()
and r.decision = 'ACCEPTED'
and r.customer_id in (SELECT c.id
FROM customers as c
WHERE c.manager_id = m.id)) as count
FROM managers as m;
其中表是经理,客户和报告。我想对每个经理进行SELECT,计算他的所有客户所做的报告数量(带有选定的属性)。这段代码的问题是,它花费了太多的时间,而且不知为何找不到更好的方法来建立这个查询。你有什么好办法吗?
我认为,一个标准的内部连接在这三个表之间的索引定义在 reports.date
, reports.customer_id
和 customers.manager_id
列中提到的 comment( 此外,考虑到 managers.id
和 customer.id
列如预期的那样是主键,它们上面已经有唯一的索引。 )从性能的角度来看就足够了。
SELECT m.id, count(r.id)
FROM customers c
JOIN managers m ON r.customer_id = c.id
JOIN reports r ON m.id = c.manager_id
WHERE r.date BETWEEN NOW() - INTERVAL '7 days' AND NOW()
AND r.decision = 'ACCEPTED'
GROUP BY m.id