PHP MySQL - 内部仅在非空时才加入

时间:2014-04-16 15:56:50

标签: php mysql inner-join

我有一个使用内部连接的mysqli SELECT查询,我注意到一个大问题:它没有选择条件的列值为null的行(因为第二个表中不存在NULL)。这是我的代码:

<?php

$sql = mysqli_connect(/* CONNECTION */);

$query =    "SELECT " .
            "e.EQUIPMENT_ID, " .
            "e.CUSTOMER_ID, " .
            "e.DESCRIPTION, " .
            "e.LOCATION, " .
            "e.JOB_SITE, " .
            "e.PROJECT_NAME, " .
            "jb.DESCRIPTION AS JOB_SITE_NAME " .
            "FROM equipments e " .
            "INNER JOIN jobsites jb ON jb.JOBSITE_ID = e.JOB_SITE " .
            "WHERE e.CUSTOMER_ID = 1 ".
            "ORDER BY e.EQUIPMENT_ID ASC";

$results = mysqli_query($sql, $query);

if(!isset($data)) $data = array(); $cc = 0;

while($info = mysqli_fetch_array($results, MYSQLI_ASSOC)){

    if(!isset($data[$cc])) $data[$cc] = array();

    ///// FROM TABLE equipments /////
    $data[$cc]['EQUIPMENT_ID'] = $info['EQUIPMENT_ID'];
    $data[$cc]['DESCRIPTION'] = $info['DESCRIPTION'];
    $data[$cc]['LOCATION'] = $info['LOCATION'];
    $data[$cc]['PROJECT_NAME'] = $info['PROJECT_NAME'];
    $data[$cc]['JOB_SITE_ID'] = $info['JOB_SITE'];

    ///// FROM TABLE jobsites /////
    $data[$cc]['JOB_SITE'] = $info['JOB_SITE_NAME'];

    $cc++;
}

print_r($data);

?>

因此,正如我所说,代码返回值,但仅当“设备”中的“JOB_SITE”列具有作业现场ID(非空)时才返回。丑陋的解决方案是使用名为“empty”的jobsite_id在表“jobsites”中创建一行,但如果我可以跳过这一行,我会。

只有在e.JOB_SITE不为空时才有加入的方法吗?

1 个答案:

答案 0 :(得分:6)

您可以在SQL查询中使用LEFT JOIN

$query =    "SELECT " .
            "e.EQUIPMENT_ID, " .
            "e.CUSTOMER_ID, " .
            "e.DESCRIPTION, " .
            "e.LOCATION, " .
            "e.JOB_SITE, " .
            "e.PROJECT_NAME, " .
            "jb.DESCRIPTION AS JOB_SITE_NAME " .
            "FROM equipments e " .
            "LEFT JOIN jobsites jb ON jb.JOBSITE_ID = e.JOB_SITE " .
            "WHERE e.CUSTOMER_ID = 1 ".
            "ORDER BY e.EQUIPMENT_ID ASC";

如果NULL VALUE

中没有JOB_SITE_NAME匹配row,则此查询将返回jb.JOBSITE_ID列的equipments