【问题标题】:MySQL, IF statement in WHERE clause?MySQL,WHERE 子句中的 IF 语句?
【发布时间】:2021-07-17 11:38:19
【问题描述】:

表:

odit_docs - 表格

id|name |regNumber|mps_id
1 |test1|123      | 1
2 |test2|124      | NULL

mps - 表格

id|name |mpsRegnomer|
1 |test1|1233       |
2 |test2|1244       |

查询:

SELECT * FROM `odit_docs` as od where IF(od.mps_id IS NOT NULL, SELECT mps.mpsRegnomer FROM mps where mps.id = od.mps_id, od.regNumber) = '123'

场景:

如果列 od.mps_id IS NOT NULL 以基于 od.mps_id mps.id 关系从其他表 mps 中选择值,但如果列 od.mps_id 为 NULL,则它应该采用列 od.regNumber我应该检查这个 if-else 语句的返回值是否等于某个值,在这种情况下它是 123 我在这种形式的查询中遇到了错误。

如果是 id 1,它应该检查 mps 表 mps.mpsRegnomer = 123 中的值,因为 od.mps_id IS NOT NULL

如果是 id 2,它应该检查 od.regNumber = 123因为 od.mps_id IS NULL

【问题讨论】:

  • 帮助我们帮助您 - 分享一些示例数据以及您尝试获得的结果
  • SELECT 子查询必须括在括号中。此外,它必须在任何情况下都只返回一行(添加 LIMIT 1)。
  • @Mureinik 完成。

标签: mysql sql


【解决方案1】:

这是您使用固定语法的查询:

SELECT * 
FROM odit_docs as od 
where IF(od.mps_id IS NOT NULL, (SELECT mps.mpsRegnomer FROM mps where mps.id = od.mps_id LIMIT 1), od.regNumber) = '123';

这会做同样的事情,但我相信它会产生更好的执行计划:

SELECT * 
FROM odit_docs as od 
LEFT JOIN mps ON mps.id = od.mps_id
WHERE (od.mps_id IS NULL and od.regNumber = '123')
      OR (mps.id = '123')

这是一个 sqlfiddle,您可以在其中对其进行测试: http://sqlfiddle.com/#!9/61e101/4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    相关资源
    最近更新 更多