mysql join两个表来获取记录

时间:2010-01-12 11:55:29

标签: mysql join foreign-keys

Hai guys,

我有两个表 Incharge 属性。我的属性表有三个字段1stIncharge,2ndIncharge和3rdIncharge。 InchargeId被设置为属性表中所有上述字段的外键..

如何编写一个连接表的select语句..我尝试了一下但没有结果

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 \\)

伙计3场P.1stIncharge,P.2ndIncharge,P.3rdIncharge有外键I.Id

修改

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

2 个答案:

答案 0 :(得分:0)

我不确定这两个表中的外键名称,但我认为你正在寻找这个:

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

答案 1 :(得分:0)

如果你的表名和列名都正确,你提供的解决方案看起来没问题(我重新格式化了):

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 )

你得到什么样的错误?