简体   繁体   English

带有条件 where 子句的 MySql 选择语句

[英]MySql select statement with conditional where clause

I am trying to write a MySql statement with a conditional where clause.我正在尝试使用条件 where 子句编写 MySql 语句。 something like this:像这样的东西:

set @price = 5000 ;设置@price = 5000;
set @city = 1324368075;设置@city = 1324368075;

 select count(*)
 from property
 where case when @price is not null then
              price < @price
       end
       and (case when @city is not null then
             CityId = @city
          end)

the variable should be included in the query only if it is not null.仅当变量不为空时,该变量才应包含在查询中。

My attempts have failed so far.到目前为止,我的尝试都失败了。 Any ideas?有任何想法吗?

Edited:编辑:

Sorry I spoke too soon ysth,对不起,我说得太早了ysth,

these two queries are supposed to yield the same count but they dont.这两个查询应该产生相同的计数,但它们不会。

在此处输入图像描述

在此处输入图像描述

Edit #2: Execution plan & indexes编辑#2:执行计划和索引

Here's the query:这是查询:

 set @CountryId = null ;
 set  @CityId = 1324368075 ;
 set @StateProvince = null ;
 set @CategoryId = null ; 
 set  @TransactionTypeId = null;
 set @Price = 5000;
 
 SELECT 
  Count(*) 
FROM 
  meerkat.property 
WHERE 
  (CASE WHEN @CountryId IS NOT NULL THEN CountryId = @CountryId ELSE 1 END)
  AND (CASE WHEN  @CityId IS NOT NULL THEN CityId = @CityId ELSE 1 END) 
  AND (CASE WHEN @CategoryId IS NOT NULL THEN CategoryId = @CategoryId ELSE 1 END) 
  AND (CASE WHEN  @StateProvince IS NOT NULL THEN StateProvince = @StateProvince ELSE 1 END) 
  AND (CASE WHEN @TransactionTypeId IS NOT NULL THEN TransactionTypeId = @TransactionTypeId ELSE 1 END) 
  AND (CASE WHEN @Price IS NOT NULL THEN Price <= @Price ELSE 1 END) 
  AND IsPublic = 1 
  AND IsBlocked = 0;

在此处输入图像描述

Thanks in advance提前致谢

If no when conditions are met, case returns null.如果满足条件时为 no,则case返回 null。 If you want each test to pass, you need to return a true value instead, so:如果您希望每个测试都通过,则需要返回一个 true 值,因此:

case when @price is not null then
          price < @price
    else 1 end
and ...

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

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