简体   繁体   中英

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:

+----+--------------------+-------+------------------+
| 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 . 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 . 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))

also be carful to close your where by ' character

i recommend using where with clouser like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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