如果数据不在表中,则mysql查询不返回结果

时间:2013-04-17 13:17:11

标签: php select mysqli

以下是几乎有效的查询:

$query  = '';
$query .= ' SELECT highway_code.charge_id, 
        highway_code.act_abbr, 
        highway_code.short_form_wording, 
        highway_code.section, 
        highway_code.set_fine,  
        highway_code_arrest_jail_tow.demerits
        ';
$query .= ' FROM highway_code, highway_code_arrest_jail_tow ';
$query .= ' WHERE highway_code.charge_id = ? ';
$query .= ' AND highway_code.section = highway_code_arrest_jail_tow.section ';
$query .= ' AND highway_code.act_abbr = highway_code_arrest_jail_tow.act_abbr ';

问题在于并非所有高速公路代码费用都有缺点,因此即使所有其他字段都适用,也不会返回任何没有缺点的费用。无论highway_code_arrest_jail_tow中是否有值,我都希望退回所有费用。

1 个答案:

答案 0 :(得分:2)

FROM子句中使用逗号分隔的表,相关列之间的相等条件意味着INNER JOIN。要强制执行从主表返回的所有记录,而不管相关表中是否存在相关记录,请改用LEFT JOIN

我将使用显式LEFT JOIN

替换隐式内连接
SELECT
  highway_code.charge_id, 
  highway_code.act_abbr, 
  highway_code.short_form_wording, 
  highway_code.section, 
  highway_code.set_fine,  
  highway_code_arrest_jail_tow.demerits
FROM
  highway_code
  LEFT JOIN highway_code_arrest_jail_tow
     /* Two relating conditions belong in the ON clause */
     ON highway_code.section = highway_code_arrest_jail_tow.section
     AND highway_code.act_abbr = highway_code_arrest_jail_tow.act_abbr
WHERE
  /* and the filtering condition remains in the WHERE */
  highway_code.charge_id = ?