在使用两个WHERE子句限制查询时,PHP查询显示没有日期的行

时间:2014-06-22 03:35:20

标签: php mysql

下面的代码回显了一个包含未来90天行的表格,这正是我想要的。它只是diplays"交易"对于有交易的日期。其他日期是空白的,这也是我想要的。

我想将表限制为仅显示交易WHERE cityid = '$cityid'。但是,当我尝试将此添加到查询时,它会忽略没有交易的日期的行。

如何将查询限制为WHERE cityid = '$cityid'并仍然显示没有交易的日期的行?

$sqlStr = 
    "SELECT c.dt, d.deal, d.dealid, d.datescheduled, d.cityid
    FROM calendar_table c
    LEFT JOIN deals d ON d.datescheduled = c.dt
    WHERE c.dt > NOW()
    ORDER BY c.dt ASC
    LIMIT 90";

echo "<table class=\"samplesrecs\">";
while ($row = mysql_fetch_array($result)) { 
    $dt = new DateTime($row["dt"], $tzFrom);  
    $dt->setTimezone($tzTo);

    echo '<tr class="class3a">';

    echo '<td style= "border-left:2px solid #ce0f07; 
            border-right:2px solid #ce0f07; 
            border-top:2px solid #ce0f07;" 
            class="sitename1">
        <a href="http://www.domain.com/login/deal.php?date='.urlencode($row["dt"]).'&cityid='.urlencode($cityid).'">'.$dt->format('l, F j, Y').'</a>
        </td>';
    echo '<td style="border-left:2px solid #ce0f07; 
            border-right:2px solid #ce0f07; 
            border-top:2px solid #ce0f07;" 
            class="sitename1">
        <a href="http://www.domain.com/login/deal.php?date='.urlencode($row["dt"]).'&cityid='.urlencode($cityid).'&dealid='.urlencode($row["dealid"]).'">'.$row["deal"].'</a>
        </td>';
}

echo '</tr>';
echo "</table>";

2 个答案:

答案 0 :(得分:2)

您可以在JOIN子句中添加其他约束:

SELECT c.dt, d.deal, d.dealid, d.datescheduled, d.cityid
FROM calendar_table c
LEFT JOIN deals d ON (
    d.datescheduled = c.dt
    AND d.cityid = "mycity"
)
WHERE c.dt > NOW() 
ORDER BY c.dt ASC
LIMIT 90

这将显示所有日期,但仅显示与指定城市一起发生的交易。

答案 1 :(得分:1)

将其添加到您的加入

$sqlStr = "SELECT c.dt, d.deal, d.dealid, d.datescheduled, d.cityid
             FROM calendar_table c
             LEFT JOIN deals d ON d.datescheduled = c.dt AND d.cityid = '$cityid'
            WHERE c.dt > NOW() 
         ORDER BY c.dt ASC
         LIMIT 90";