简体   繁体   English

MySQL SELECT语句的语法以及IF语句内的子查询

[英]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. 我在使用IF语句中的子查询来获取MySQL SELECT语句的语法正确性时遇到麻烦。


EDIT 编辑

I need to include subqueries in the db query if particular values have been specified. 如果已指定特定值,则需要在db查询中包括子查询。 In this particular example, if they've specified the Item then only fetch rows where Item and Price also match specific values. 在此特定示例中,如果他们指定了Item,则仅获取Item和Price也匹配特定值的行。

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) 这不起作用(如果Item = Dresss,则应检查价格)

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. 使用'$300'大概与一个数字进行比较。 (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)

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

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