表:
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'
场景:
如果 column od.mps_id
IS NOT NULLmps
根据od.mps_id
<=>mps.id
关系从其他表中选择值,但如果 columnod.mps_id
为 NULL 它应该od.regNumber
在最后使用 column我应该检查这个if-else 语句的返回值是否等于这种情况下的某个值它是123我在这种形式的查询中出错。
如果id 1它应该检查值是否来自mps表mps.mpsRegnomer = 123
,因为 od.mps_id 不是 NULL
在id 2 的情况下,它应该检查 if od.regNumber = 123
,因为 od.mps_id IS NULL
这是您使用固定语法的查询:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句