简体   繁体   English

MySQL 如何进行 3 表连接

[英]MySQL How to do a 3 table join

I'm trying to perform a 3 table join on MySQL in order to achieve something like the diagram below.我正在尝试在 MySQL 上执行 3 表连接,以实现如下图所示的效果。

在此处输入图片说明

The main problem I'm having is that I only want to work with the records of table A which has 100 records so if there are no relationships for the right tables I would like to see a null.我遇到的主要问题是我只想处理具有 100 条记录的表 A 的记录,因此如果正确的表没有关系,我希望看到空值。

This all works fine when only table A and B are involved but when I try to do the third join with C I'm getting more than the original 100 records, I'm getting 130 which I believe is because is adding the records that match BC with duplicate data from table A.当只涉及表 A 和 B 时,这一切都很好,但是当我尝试与 C 进行第三次连接时,我得到的记录超过了原来的 100 条记录,我得到了 130 条记录,我相信这是因为正在添加匹配的记录BC 具有来自表 A 的重复数据。

What am I missing?我错过了什么?

This is the SQL I currently have that returns correctly 100 records这是我目前拥有的正确返回 100 条记录的 SQL

SELECT count(A.id)
FROM tableA A
LEFT JOIN TableB B ON B.id = A.b_id

This is what I'm trying to do that is returning more than the original 100 records for Table A.这就是我正在尝试做的事情,即为表 A 返回超过原始 100 条记录。

SELECT count(A.id)
FROM tableA A
LEFT JOIN TableB B ON B.id = A.b_id
LEFT JOIN TableC C ON C.id = B.c_id

This could be resolved by a JOIN to a subquery rather than a table.这可以通过JOIN到子查询而不是表来解决。

If you had unique Ids to join to, it would simply be like you've tried already (arbitrary example):如果您有唯一的 ID 可以加入,那就像您已经尝试过一样(任意示例):

SELECT * from table1 t1
LEFT JOIN table2 t2 on t2.id = t1.id
LEFT JOIN table3 t3 on t3.id = t2.id

If, however the id field in table3 wasn't unique, you'd get multiple rows for each duplicate.但是,如果table3id字段不是唯一的,则每个重复项都会得到多行。 You could resolve this by:您可以通过以下方式解决此问题:

SELECT * from table1 t1
LEFT JOIN table2 t2 on t2.id = t1.id
LEFT JOIN (SELECT * FROM table3 GROUP BY id) t3 on t3.id = t2.id

So, using your example (assuming only the third join has duplicates), something like:因此,使用您的示例(假设只有第三个连接具有重复项),例如:

SELECT count(A.id)
FROM tableA A
LEFT JOIN TableB B ON B.id = A.b_id
LEFT JOIN (SELECT * FROM TableC GROUP BY id) C ON C.id = B.c_id

...should do the trick. ...应该可以解决问题。 This is down to assumption of your table and data structure, so you might want to make the asterisk more explicit.这取决于您的表和数据结构的假设,因此您可能希望使星号更明确。

SELECT count(distinct A.id)
FROM tableA A
LEFT JOIN TableB B ON B.id = A.b_id
LEFT JOIN TableC C ON C.id = B.c_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM