繁体   English   中英

多个字段上的 Mysql where 子句,其中一个可能为空

[英]Mysql where clause on multiple fields which one might be null

在我的产品表中,我有 2 列: pricediscounted_price ,其中discounted_price大部分时间为空,除非该产品有促销:

+----+--------------------+-------+------------------+
| id | name               | price | discounted_price |
+----+--------------------+-------+------------------+
|  1 | test 1             | 79.00 |       null       |
|  2 | test 2             | 50.00 |       45.00      |
+----+--------------------+-------+------------------+

id 为2的产品现在正在促销并且已discounted_price 现在我想查询产品以获得比 50 便宜的产品,但在我的查询中我需要检查discounted_price是否为null然后查看price ,否则查看discounted_price 谷歌所说的正在使用:

$products = Product::where('coalesce(price, discounted_price) <= 50);

但它不起作用:(

或者,您可以使用子查询,如下所示:

$q = 50;
$product = Product::where(function($query) use($q) {
      $query->where('discounted_price', '<=', $q)
            ->orWhere('price', '<=', $q)
   })
   ->get();

您可以使用whereRaw而不是wherewhere(DB::raw('coalesce(price, discounted_price') <= 50))

也要小心用'字符关闭你的位置

我建议使用 where 与 clouser 这样的:

 $products = Product::where(function ($query)
        {
            $query->where('discounted_price',null)->where('price','<=',50);
        })->orWhere('discounted_price','<=',50)->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM