我正在尝试连接两个表并从“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 的所有位置。如果没有“适当”的描述,那么如果我只显示简短的描述就更好了
所以我希望达到的结果是
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 和 Leicester 而不是 lester
谢谢你的帮助
最佳答案
您可以为此使用 SQL 函数 COALESCE()
。
此函数在其参数中使用第一个非空值。
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
,可以重新加入location表。
我要指出的是,为了让事情变得更简单,我添加了表别名以区分不同的表。
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
表用于开始和结束位置。
关于php - 使用 LEFT JOIN 选择 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18814540/