0

我有一个 MySQL 查询,它从不同的表中挑选不同的数据来构建报告。例子:

SELECT
  u.id,
  u.first_name,
  u.last_name,
  (select count(*) from monkeys where owner_id = u.id) as pet_monkeys,
  ((select count(*) from speeding_tickets where owner_id = u.id) + (select count(*) from parking_tickets where owner_id = u.id)) as moving_violations,
FROM
  user as u
WHERE
  u.id = 12345

在实际代码中,大约有 20 个子选择从不同的表中提取统计信息。这个查询也非常缓慢。

有没有更好的方法来使用 JOIN 或 UNION 或其他东西来组织上述查询?

4

1 回答 1

0

在这种情况下,它们都链接回同一个表用户,您可以将它们连接在一起进行分组和计数,这样会快得多。还要确保你建立了正确的索引

 SELECT
  u.id,
  max(u.first_name),
  max(u.last_name),
  count(m.owner_id) as pet_monkeys,
  count(s.owner_id) + count(p.owner_id) as moving_violations
FROM
  user as u, monkeys m, speeding_tickets s, parking_tickets p
WHERE
  u.id = 12345 and
  u.id = m.owner_id and
  u.id = p.owner_id and
  u.id = s.owner_id
GROUP BY u.id
于 2013-09-06T03:31:14.820 回答