【问题标题】:How to join three different tables in MySQL如何在 MySQL 中连接三个不同的表
【发布时间】:2020-11-12 09:27:27
【问题描述】:

我正在使用 MySQL v5.5

我只是 left joining 两张表并获得了我的准确数据。

但是当我尝试在这里添加另一个表时,结果并不准确。

Here is the fiddle

请告诉我我做错了什么? 非常感谢。

【问题讨论】:

  • 在使用聚合函数的查询中连接多个表时,您将观察到一种称为连接乘法的不准确性。对于主表中的同一行,第一个连接表中的每一行将具有与第二个连接表中的行数一样多的副本。解决方案 - 在子查询中聚合然后加入。

标签: mysql join left-join


【解决方案1】:

对于给定的事件,每个表中有多个匹配项,因此连接将行数相乘,您会得到错误的结果。

我建议在子查询中预先聚合:

select e.event_id, e.title, e.description, e.event_date, e.image, 
    coalesce(d.total_amount,0) as total,
    coalesce(d.total_donors, 0) as total_donors,
    coalesce(v.total_volunteers, 0) as total_volunteers
from event e 
left join (
    select event_id, count(*) as total_volunteers
    from volunteer 
    group by event_id
) v on v.event_id = e.event_id
left join (
    select event_id, sum(amount) as total_amount, count(*) as total_donors
    from donation 
    group by event_id
) d on d.event_id = e.event_id 

【讨论】:

  • 另一个问题:考虑到我有 5-6k 行数据,子查询的执行速度会慢一些吗?
【解决方案2】:

我建议您尝试删除 LEFT,将其保留为 JOIN,我曾经遇到过同样的问题,这个 tutorial 真的帮助了我

【讨论】:

  • 不。没用。这可能对您的情况有所帮助,但对我没有用。感谢您的回复:)
猜你喜欢
  • 1970-01-01
  • 2017-03-01
  • 1970-01-01
  • 2016-11-19
  • 2021-11-27
  • 1970-01-01
  • 2014-02-24
  • 1970-01-01
  • 2018-03-04
相关资源
最近更新 更多