0

这是几乎有效的查询:

$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.

4

1 回答 1

2

在子句中使用逗号分隔的表,FROM相关列之间的相等条件意味着INNER JOIN. 要强制从主表返回所有记录,而不管相关表中是否存在相关记录,请改用 a 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 = ?
于 2013-04-17T14:25:43.500 回答