如何从连接5个不同表的mysql数据库中检索数据

时间:2017-02-16 14:04:10

标签: php mysql inner-join

我正在尝试从5个不同的表中检索mysql数据库中的数据,但它没有按预期工作,并且没有显示任何内容。

表是:

  • site_info
  • site_coordinates
  • OWNER_INFO
  • subcontractor_info
  • company_info

site_info:

  • 的siteID
  • companyID -siteNAME
  • OWNERID
  • subcontractorID
  • equipmentTYPE

站点坐标:

  • 的siteID

  • 纬度

  • 经度

  • 高度

OWNER_INFO:

  • OWNERID
  • OWNERNAME
  • ownerCONTACT

subcontractor_info:

  • subcontractorID
  • subcontractorCOMPANY
  • subcontractorNAME
  • subcontractorCONTACT

company_info:

  • companyID
  • COMPANYNAME

mysql查询:

select 
     site_info.siteID,site_info.siteNAME ,site_info.equipmentTYPE,site_coordinates.latitude,site_coordinates.longitude,site_coordinates.height ,owner_info.ownerNAME,owner_info.ownerCONTACT,company_info.companyNAME,subcontractor_info.subcontractorCOMPANY,subcontractor_info.subcontractorNAME,subcontractor_info.subcontractorCONTACT   
from `site_info`
INNER JOIN `owner_info`
  on site_info.ownerID = owner_info.ownerID
INNER JOIN `company_info`
  on site_info.companyID = company_info.companyID
INNER JOIN `subcontractor_info`
  on site_info.subcontractorID = subcontractor_info.subcontractorID
INNER JOIN `site_coordinates`
  on site_info.siteID=site_coordinates.site_id
where owner_info.ownerID = 159

我的错误在哪里,有没有更好的方法呢?

2 个答案:

答案 0 :(得分:1)

我只需要改为LEFT JOIN即可解决。

所以更新的查询看起来:

select 
site_info.siteID,site_info.siteNAME ,site_info.equipmentTYPE,site_coordinates.latitude,site_coordinates.longitude,site_coordinates.height ,owner_info.ownerNAME,owner_info.ownerCONTACT,company_info.companyNAME,subcontractor_info.subcontractorCOMPANY,subcontractor_info.subcontractorNAME,subcontractor_info.subcontractorCONTACT from `site_info`
LEFT JOIN `owner_info`
on site_info.ownerID = owner_info.ownerID 
LEFT JOIN `company_info` 
on site_info.companyID = company_info.companyID
LEFT JOIN `subcontractor_info` 
on site_info.subcontractorID = subcontractor_info.subcontractorID
LEFT JOIN `site_coordinates` 
on site_info.siteID=site_coordinates.siteID 
where owner_info.ownerID = 159 

感谢您的意见和回答

答案 1 :(得分:0)

Query在语法上是正确的。由于您遇到输出问题,请检查您的Relation Algebra。你在他们之间使用正确的JOIN条件吗?如果两个表中的每个表都有一个公共属性,您可以执行自然连接,即不给出条件,公共属性将被整理出来,我会使用ALIAS'AS'关键字编写这样复杂的查询。

SELECT
     site_info.siteID,
     site_info.siteNAME,
     site_info.equipmentTYPE,
     site_coordinates.latitude,
     site_coordinates.longitude,
     site_coordinates.height,
     owner_info.ownerNAME,
     owner_info.ownerCONTACT,
     company_info.companyNAME,
     subcontractor_info.subcontractorCOMPANY,
     subcontractor_info.subcontractorNAME,
     subcontractor_info.subcontractorCONTACT        
FROM `site_info` AS SI JOIN `owner_info` AS OI
  ON SI.ownerID = OI.ownerID 
  JOIN `company_info` AS CI
  ON SI.companyID = CI.companyID 
  JOIN `subcontractor_info` AS SUBI
  ON SI.subcontractorID = SUBI.subcontractorID 
  JOIN `site_coordinates` AS SC
  ON SI.siteID=SC.site_id
WHERE owner_info.ownerID = 159;