[英]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. 然后我也想添加第3张表,但我不能让它工作。
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? 您在会员中与用户和公司分享您的“id”列,这是您的意图吗? Really your tables should have differing IDs and only join on foreign keys.
实际上你的表应该有不同的ID,只能加入外键。
eg 例如
Members.id = 12345 Members.CompanyFk = 45632 Members.id = 12345 Members.CompanyFk = 45632
Companies.id = 45632 Companies.id = 45632
Join members.companyfk to companies.id 将members.companyfk加入companies.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.