简体   繁体   中英

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.

在此处输入图片说明

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.

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.

What am I missing?

This is the SQL I currently have that returns correctly 100 records

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.

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.

If you had unique Ids to join to, it would simply be like you've tried already (arbitrary example):

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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