简体   繁体   English

mysql join两个表获取记录

[英]mysql join Two tables to get records

Hai guys, 海人,

I have two tables Incharge and property . 我有两个表Inchargeproperty My property table has three fields 1stIncharge,2ndIncharge and 3rdIncharge. 我的属性表具有三个字段1stIncharge,2ndIncharge和3rdIncharge。 InchargeId is set as foreign key for all the above fields in the property table.. 对于属性表中所有上述字段,将InchargeId设置为外键。

How to write a select statement that joins both the table.. I ve tried a bit but no result 如何编写将两个表都连接在一起的选择语句。.我尝试了一下,但没有结果

select P.Id,P.Name,P.1stIncharge,P.2ndIncharge,P.3rdIncharge,I.Id from 
Property as P join Incharge as I where (\\How to give condition here \\)

Guys 3 fields P.1stIncharge, P.2ndIncharge, P.3rdIncharge has foreign key I.Id 伙计们3个字段P.1stIncharge,P.2ndIncharge,P.3rdIncharge具有外键I.Id

Edit: 编辑:

select P.Id,P.Name,P.1stIncharge,P.2ndIncharge,P.3rdIncharge,I1.Id from 
Property as P 
inner join Incharge as I1 on I1.Id=P.1stIncharge 
inner join Incharge as I2 on I2.Id=P.2ndIncharge  
inner join Incharge as I3 on I3.Id=P.3rdIncharge

and this query working

I'm not sure about your foreign key names from both tables, but I think you're looking for this: 我不确定两个表中的外键名称,但我认为您正在寻找以下内容:

SELECT P.Id, P.Name, P.1stIncharge, P.2ndIncharge, P.3rdIncharge, I.Id
FROM Property as P INNER JOIN Incharge as I ON P.InchargeId = I.Id

If your table and column names are correct, your provided solution looks ok (I reformatted it): 如果您的表名和列名正确,则您提供的解决方案看起来还可以(我将其重新格式化):

SELECT
  P.Id, P.Name, P.1stIncharge, P.2ndIncharge, P.3rdIncharge,
  I1.Id
FROM Property AS P
JOIN Incharge AS I1 ON ( I1.Id = P.1stIncharge )
JOIN Incharge AS I2 ON ( I2.Id = P.2ndIncharge )
JOIN Incharge AS I3 ON ( I3.Id = P.3rdIncharge )

What kind of error do you get? 您会遇到哪种错误?

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

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