2017-08-23 92 views
2

我可以在IN語句中使用CASE嗎?我使用的是mysql服務器,下面是查詢。CASE檢查IN子句中的NULL值

SELECT Id from Tenant 
where TenantId IN (
        CASE WHEN 'someVariable' is NULL 
        THEN (select customer_id from Partners where partner_id = 'abc') 
        ELSE ('xyz1','xyz2','xyz3') 
        END 
       ) 

這將引發錯誤: Error Code: 1241. Operand should contain 1 column(s)

我需要檢查:在第Null值,然後取決於結果需要或者火選擇的「合作伙伴」表或只是通過一個列表預定義的字符串轉換爲IN子句。 在此先感謝。

+0

您可以創建SQL演示? http://sqlfiddle.com/ –

回答

0

你可以試試:

SELECT Id from Tenant 
WHERE TenantId IN (select customer_id from Partners where partner_id = 'abc') 
      AND somevariable IS NULL 
     OR TenantId IN ('xyz1','xyz2','xyz3') AND somevariable IS NOT NULL 

或作爲替代

SELECT Id from Tenant 
where TenantId IN (
        CASE WHEN 'someVariable' is NULL 
        THEN (select customer_id from Partners where partner_id = 'abc') 
        ELSE (select 'xyz1' AS id UNION ALL select 'xyz2' UNION ALL Select 'xyz3') 
        END 
       )