[英]Mysql where clause on multiple fields which one might be null
In my products table, I have 2 columns: price
and discounted_price
in which discounted_price
is null most of the time unless there is a promotion for that product:在我的产品表中,我有 2 列:
price
和discounted_price
,其中discounted_price
大部分时间为空,除非该产品有促销:
+----+--------------------+-------+------------------+
| id | name | price | discounted_price |
+----+--------------------+-------+------------------+
| 1 | test 1 | 79.00 | null |
| 2 | test 2 | 50.00 | 45.00 |
+----+--------------------+-------+------------------+
The product with id of 2
is now on promotion and has discounted_price
. id 为
2
的产品现在正在促销并且已discounted_price
。 Now I want to query products to get products cheaper than 50 but in my query I need to check if discounted_price
is null
then look into price
, otherwise look into discounted_price
.现在我想查询产品以获得比 50 便宜的产品,但在我的查询中我需要检查
discounted_price
是否为null
然后查看price
,否则查看discounted_price
。 What Google said is using:谷歌所说的正在使用:
$products = Product::where('coalesce(price, discounted_price) <= 50);
But it's not working :(但它不起作用:(
Alternative, you can use sub query, like this :或者,您可以使用子查询,如下所示:
$q = 50;
$product = Product::where(function($query) use($q) {
$query->where('discounted_price', '<=', $q)
->orWhere('price', '<=', $q)
})
->get();
you can use whereRaw
instead of where
or where(DB::raw('coalesce(price, discounted_price') <= 50))
您可以使用
whereRaw
而不是where
或where(DB::raw('coalesce(price, discounted_price') <= 50))
also be carful to close your where by '
character也要小心用
'
字符关闭你的位置
i recommend using where with clouser like this:我建议使用 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.