簡體   English   中英

MySQL,WHERE 子句中的 IF 語句?

[英]MySQL, IF statement in WHERE clause?

桌子:

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'

場景:

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我在這種形式的查詢中遇到錯誤。

如果id 為 1 ,它應該檢查 mps 表中的值mps.mpsRegnomer = 123因為 od.mps_id 不是 NULL

如果id 為 2 ,它應該檢查od.regNumber = 123因為 od.mps_id 是 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM