简体   繁体   English

MySQL,WHERE 子句中的 IF 语句?

[英]MySQL, IF statement in WHERE clause?

Table:桌子:

odit_docs - table odit_docs - 表

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

mps - table mps - 表

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

The query:查询:

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'

The scenario:场景:

If column od.mps_id IS NOT NULL to select value from other table mps based on od.mps_id <=> mps.id relationship, but if column od.mps_id is NULL it should take column od.regNumber at the end I should check if returned value from this if-else statement is equal to some value in this case it's 123 I got error in this form of query. If column od.mps_id IS NOT NULL to select value from other table mps based on od.mps_id <=> mps.id relationship, but if column od.mps_id is NULL it should take column od.regNumber at the end I should check if这个if-else 语句的返回值等于某个值,在这种情况下它是123我在这种形式的查询中遇到错误。

In case with id 1 it should check if value from mps table mps.mpsRegnomer = 123 , because od.mps_id IS NOT NULL如果id 为 1 ,它应该检查 mps 表中的值mps.mpsRegnomer = 123因为 od.mps_id 不是 NULL

In case with id 2 it should check if od.regNumber = 123 , because od.mps_id IS NULL如果id 为 2 ,它应该检查od.regNumber = 123因为 od.mps_id 是 NULL

This is your query with fixed syntax:这是您使用固定语法的查询:

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';

This will do the same thing but I believe it will generate a better execution plan:这将做同样的事情,但我相信它会产生更好的执行计划:

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')

Here's a sqlfiddle where you can test it: http://sqlfiddle.com/#!9/61e101/4这是一个 sqlfiddle,您可以在其中对其进行测试: http://sqlfiddle.com/#!9/61e101/4

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

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