简体   繁体   中英

Syntax for MySQL SELECT statement with a subquery within the IF statement

I'm having trouble getting the syntax right for a MySQL SELECT statement with a subquery within the IF statement.


EDIT

I need to include subqueries in the db query if particular values have been specified. In this particular example, if they've specified the Item then only fetch rows where Item and Price also match specific values.

SELECT * FROM Products WHERE Products.Color = :Colors_like
AND IF(Item = IS NOT NULL OR Item != '' 
(Item = :Item AND Products.Price <= (SELECT $MaxPrice_Item FROM Lifestyle WHERE User_id = $User_id) ) 
) 

I've included a simplified snippet below with hardcoded values


This works correctly:

SELECT * FROM Products WHERE Color = 'Black'
AND IF (Item = 'Dresses', 1, 0) = 1

This doesn't work (If Item = Dresses, it should check Price)

SELECT * FROM Products WHERE Color = 'Black'
AND IF (Item = 'Dresses' (SELECT * FROM Products WHERE Price < '$300'), 1, 0) = 1

I've tried every format I could think of, but I can't seem to get the statement to work.

You need a something before the subselect:

SELECT *
FROM Products
WHERE Color = 'Black' AND
     IF (Item = 'Dresses' ?? (SELECT * FROM Products WHERE Price < '$300'), 1, 0) = 1
--------------------------^

I am not quite sure what, because there are many other problems, such as:

  • Using * where a scalar subquery is expected.
  • Using '$300' to presumably compare against a number. (Or worse, storing a "price" as a string.)
  • Having a scalar subquery return multiple rows.

If you want conditional logic, then this is what I think you want:

SELECT p.*
FROM Products p
WHERE p.Color = 'Black' AND
      (p.Item <> 'Dresses' OR p.Price < 300)

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