使用LEFT JOIN进行MySQL选择

时间:2013-09-15 16:12:44

标签: php mysql left-join

我正在尝试加入两个表并从'railstp'中选择。我简化了表格。

表'railstp'如下所示

count  startdate   startlocation    atoc

  1    2013-09-28     lester          a
  2    2013-09-28     nottm           a
  3    2013-09-20     lester          a   
  4    2013-09-28     birm            a 

表'位置'如下所示

count  startlocation  goodlocation

  1      lester         Leicester
  2      nottm          Nottingham

我试图从表'location'获取'正确'(goodlocation)描述来替换缩写描述(startlocation),并且还选择所有位于2013-09-28的startdate的位置。如果没有“正确”的描述,如果我只是显示缩写描述

那就太棒了

所以我希望实现的结果是

2013-09-28    Leicester    a
2013-09-28    Nottingham   a
2013-09-28    birm         a

我的代码如下: -

require('connect_db.php');
mysqli_select_db($mysql_link,"Timetable");
function show_records($mysql_link)
{
$q="SELECT railstp.startdate,railstp.startlocation,railstp.atoc,location.startlocation,location.goodlocation
FROM railstp
LEFT JOIN location
ON railstp.startlocation=location.startlocation
WHERE railstp.startdate='2013-09-28'
ORDER BY startdate";

$r=mysqli_query($mysql_link,$q);

if ($r)
{
echo "<Table id='customers'>
<tr>
<th>From</th>
<th>Departing</th>
<th>ATOC</th>
</tr>";

while ($row=mysqli_fetch_array($r,MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>".$row['startdate']."</td>";
echo "<td>".$row['startlocation']."</td>";
echo "<td>".$row['atoc']."</td>";
echo "</tr>";
}
echo "</Table>";
}
else {echo '<p>'.mysqli_error($mysql_link).'</p>' ;}
}
show_records($mysql_link);
mysqli_close($mysql_link);

选择没有显示'正确'(goodlocation)描述 - 即它应该显示Nottingham而不是nottm而莱斯特而不是lester

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

您可以使用SQL函数COALESCE()

此函数在其参数中使用第一个非null值。

SELECT railstp.startdate,
       COALESCE(location.goodlocation, railstp.startlocation) as startloc,
       railstp.atoc
FROM railstp
LEFT JOIN location
ON railstp.startlocation=location.startlocation
WHERE railstp.startdate='2013-09-28'
ORDER BY startdate

所以在这里,如果location.goodlocation为NULL,则使用railstp.startlocation

请参阅SQL-fiddle

<强>更新

如果您想添加endlocation,可以再次加入位置表。 我要指出,为了使事情变得更容易,我已经添加了表别名来区分不同的表。

SELECT r.startdate,
       COALESCE(l1.goodlocation, r.startlocation) as startloc,
       COALESCE(l2.goodlocation, r.endlocation) as endloc,
       r.atoc
FROM railstp r
LEFT JOIN location l1
ON r.startlocation = l1.startlocation
LEFT JOIN location l2
ON r.endlocation = l2.startlocation
WHERE r.startdate='2013-09-28'
ORDER BY r.startdate

当然,如果location表用于开始和结束位置,那么这就是

答案 1 :(得分:1)

查询中有两列具有相同名称的列。没有办法在php代码中告诉你想要哪一个,所以第一个被选中。使用as重命名其中一个:

SELECT rs.startdate, rs.startlocation as shortstartlocation, rs.atoc,
       coalesce(l.startlocation,  rs.startlocation) as startlocation,
       l.goodlocation
FROM railstp rs LEFT JOIN
     location l
      ON rs.startlocation = l.startlocation
WHERE rs.startdate = '2013-09-28'
ORDER BY startdate