我的查询中有什么错误?我试图从多个表中选择数据

时间:2017-11-08 14:15:46

标签: mysql wordpress join

我正在使用包含许多表的MySQL数据库。我有4个表:

SITE_LOCATION:

siteID(PRIMARY KEY)
locationName
lat
long

雇员:

employeeID(PRIMARY KEY)
employeeName

inspection_info:

inspectionID(PRIMARY KEY)
inspectionDate
employeeID

inspection_site:

inspectionID(PRIMARY KEY)

siteID(PRIMARY KEY)

我在 inspection_site

中有值
siteID 1 | inspectionID 1
siteID 1 | inspectionID 2

所以我的查询必须选择这两个值但不会发生它选择第一个或第二个

SQL查询:

$sql = $wpdb->prepare("select 
           l.locationName
           , n.inspectionDate
           , e.employeeName
      from site_location l
      LEFT  
      JOIN inspection_site s
        on l.siteID = s.siteID
      LEFT
        JOIN inspection_info n
        on n.inspectionID = s.inspectionID
        LEFT
      JOIN employeeName e
        on n.employeeID=e.employeeID
         where 
        l.locationName = %s
        AND 
        e.employeeID = %d
        AND 
        n.inspectionID = %d
       ",$site_name,$soldier_name, $inspection_date);

     $query_submit =$wpdb->get_results($sql, OBJECT);

enter image description here

1 个答案:

答案 0 :(得分:0)

我解决了问题

在SQL查询中 WHERE 我指定与

匹配
  • LOCATIONNAME
  • EMPLOYEEID
  • inspectionID

inspectionID 字段中,它包含 emplyee 表的关系,因此它会选择与该ID对应的单个值。

因此,解决方案是仅针对位置名称

WHERE 中的条件进行广告

sql查询:

$sql = $wpdb->prepare("select 
       l.locationName
       , n.inspectionDate
       , e.employeeName
  from army_site_location l

  JOIN inspection_site s
    on l.siteID = s.siteID

    JOIN inspection_info n
    on n.inspectionID = s.inspectionID

  JOIN employee e
    on n.employeeID=e.employeeID
    where 
    l.locationName = %s"
    ,$site_name);

 $query_submit =$wpdb->get_results($sql, OBJECT);