简体   繁体   中英

How to inner join 3 tables using mySQL?

I have joined two tables as below correctly

SELECT m.id as mid, c.id as cid FROM members m inner join companies c on m.id=c.id

and then I wanted to add a 3rd table also, but I can not get it working.

SELECT m.id as mid, c.id as cid, u.id as uid FROM members m inner join companies c on m.id=c.id inner join users u on m.id=u.id

What am I missing here?

Switch them from inner joins to left joins.

If you use the inner join, and a result does not exist in all three tables, it will be excluded, appearing to fail/not return results.

SELECT m.id as mid, c.id as cid, u.id as uid 
FROM members m 
left join companies c on m.id=c.id 
left join users u on m.id=u.id

That should take care of all the issues you are seeing.

You're sharing your "id" column in Members with both users and companies, was this your intention? Really your tables should have differing IDs and only join on foreign keys.

eg

Members.id = 12345 Members.CompanyFk = 45632

Companies.id = 45632

Join members.companyfk to companies.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