【问题标题】:condition in where clause based on a row's id基于行 ID 的 where 子句中的条件
【发布时间】:2017-03-17 12:58:30
【问题描述】:

我对 MySQL 很陌生,但想知道如何执行以下操作:

SELECT name from table 
if the id=1 then SELECT name WHERE '%first%'

else if the id in (2,3,4) then SELECT name

基本上,如果 id 为 1,我想检查名称中的字符串“first”,如果 id 为 2、3 或 4,则不检查任何字符串。有没有简单的方法可以做到这一点?我只找到了 IF 函数,但不能在其中使用 2 个条件。此外,该表不仅仅是 ID 1、2、3、4,所以我不能只说其他;我仍然需要检查 id 是否在 (2,3,4) 中。

感谢您的帮助!

【问题讨论】:

    标签: mysql sql select conditional-statements


    【解决方案1】:

    您可以使用andor 的组合。

    SELECT name from table 
    where (id=1 and name like '%first%') 
    or id in (2,3,4)
    

    编辑:基于 OP 对应该应用于 id 的 1、2、3、4 的另一个条件的评论

    SELECT name from table 
    where birthyear=1990 
    and ((id=1 and name like '%first%') or id in (2,3,4))
    

    【讨论】:

    • 这就是我的想法,但现在如果我有第三个条件同时适用于 if id=1 和 id=2,3,4 ,例如birthyear = 1990
    • 该死,完美。我没有意识到您可以将类似的条件放在 where 之后,然后再添加更具体的条件。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2017-12-10
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多