两个AND语句的MySQL查询优先级

时间:2014-02-04 17:35:27

标签: php mysql sql

以下是我目前正在使用的代码的摘录:

假设$product=Onion& $area=Bulua

$crop_query = $db->query(
                    "SELECT Crop, Price, DateUpdated, Area FROM crops 
                    WHERE Crop = '{$product}' 
                    AND `DateUpdated` = (SELECT max( `DateUpdated` )FROM crops WHERE Crop = '{$product}' ) 
                    AND `Area` = '{$area}'");

                    $result = $crop_query->fetch(PDO::FETCH_OBJ); 
                    $message = "The current price of {$result->Crop} is P{$result->Price}/kg, as of {$result->DateUpdated} in {$result->Area} Market.";            
echo $message;

SQL表摘录:

Crop    ID  Price   DateUpdated             Area
Onion   1   75      2011-01-26 14:30:00     Cogon
Onion   2   200     2012-02-22 14:30:00     Bulua

然后,上面的代码将成功打印出所需的输出:

洋葱的当前价格 P200 / kg, 2012-02-22 14:30:00 Bulua 市场。“

然而,当我将$ area的值更改为$area = Cogon时会抛出错误。我注意到它的优先级仅在DateUpdated而不是AreaDateUpdated

编辑:澄清以下评论

  • 除非我更改$ area的值,否则整个过程都有效 BuluaCogon
  • 错误是:尝试获取非对象的属性。这可能是由于DateUpdated在查询中被优先考虑

现在正在运作。谢谢你的关注。 :) 我会尽可能地发布另一个答案。

1 个答案:

答案 0 :(得分:0)

检查您的数据和查询。如果没有返回任何行,则$result将为false,因此您无法$result->Crop

你应该这样做:

$result = $crop_query->fetch(PDO::FETCH_OBJ);
if ($result) {
  // Returned results, do something ...
}

另外,请考虑将查询简化为:

SELECT Crop, Price, DateUpdated, `Area`
  FROM crops 
  WHERE Crop = '{$product}' 
  AND `Area` = '{$area}'
  ORDER BY DateUpdated DESC
  LIMIT 1