我有一个这种形式的 MYSQL 查询:
SELECT
employee.name,
totalpayments.totalpaid
FROM
employee
JOIN (
SELECT
paychecks.employee_id,
SUM(paychecks.amount) totalpaid
FROM
paychecks
GROUP BY
paychecks.employee_id
) totalpayments on totalpayments.employee_id = employee.id
我最近发现以这种形式返回的速度要快得多:
SELECT
employee.name,
(
SELECT
SUM(paychecks.amount)
FROM
paychecks
WHERE
paychecks.employee_id = employee.id
) totalpaid
FROM
employee
令我惊讶的是速度会有所不同,并且较低的查询会更快。我更喜欢上式进行开发,因为我可以独立运行子查询。
有没有办法获得“两全其美”:快速结果返回并能够单独运行子查询?