【问题标题】:How to add if elseif condition in where clause on mysql selection?如何在mysql选择的where子句中添加if elseif条件?
【发布时间】:2017-10-02 13:19:24
【问题描述】:

我正在根据 3 个基本条件选择数据,这不是问题,问题是 如果第一个条件满足,那么它不应该像 if else 那样考虑其余两个条件,但如果第一个条件是false 那么它只进入第二个而不是第三个,就像 if elseif 一样,如果前两个条件不满足,那么它将只考虑第三个。

但在 mysql 中,当我使用 OR & AND 时,它会同时考虑所有 3 个条件。

像这样:-

SELECT * FROM `table` WHERE 'main-condition' and ('1st condition' or '2nd condition' or '3rd condition');

在此之后,我还尝试在 where 子句中使用 IF,但它也给出了与 OR 相同的结果。

代码:-

SELECT * FROM `table` WHERE 'main-condition' and (IF('1st condition',true,IF('2nd condition',true,IF('3rd condition',true,false))));

实际查询:-

SELECT 'filter','car-name' FROM `car` WHERE (((`id` = ? and `type` = 'car')and(IF((find_in_set('new car',`filter`) > 0),true,IF((find_in_set('new',`filter`) > 0, true,if((`filter`=""),true,false))))));

它给出输出

但我需要这样的输出

如果有人知道如何处理此类查询,请回答我。

谢谢

【问题讨论】:

标签: php mysql


【解决方案1】:

为此,您需要以不同的条件迭代数据库中存在的所有记录。所以更好的是获取所有可能的所有记录,然后使用 PHP 脚本进行过滤。

【讨论】:

    【解决方案2】:

    我对此进行了 2-3 天的研究,然后才发现我们无法获得我上面提到的所需输出,因为 mysql 查询是针对表行单独执行的,而不是针对整个表执行的。

    但我通过使用 mysql Group_concat()

    解决了这个问题

    查询:-

    SELECT Group_concat( CASE WHEN (find_in_set('new car',`filter`) > 0) THEN car-name END separator ',') exactCars,Group_concat( CASE WHEN (find_in_set('new',`filter`) > 0) THEN car-name END separator ',') possibleCars,Group_concat( CASE WHEN (`filter`="") THEN car-name END separator ',') defaultCars, FROM `car` WHERE (`id` = ? and `type` = 'car');
    

    这提供了这样的输出

    现在只需使用 php Explode() 与结果然后得到所需的数据 喜欢

    $exactCars=explode(',',$reult->exactCars);
    

    输出为

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 2012-10-09
      • 2012-07-26
      • 2013-12-23
      • 2021-10-07
      • 1970-01-01
      相关资源
      最近更新 更多