首页 > 解决方案 > How to correctly use an IF statment to add a specific WHERE condition?

问题描述

I am not so into database and I have a problem working on a MySql query that involve an IF statment.

I ahve this litle query (that works fine):

(LCZ1.country_id = (SELECT LCZ2.country_id FROM Localization AS LCZ2 WHERE LCZ2.id = 5))

that return an integer value (1 or 2) into LCZ1.country_id.

I want to use an IF statment to do something if the returned value is 1 and something else if it is 2.

I was trying to do something like this (this IF statment should add an AND condition to a WHERE clause):

IF(LCZ1.country_id = 1)
BEGIN
AND
     LCZ1.country_id is not null
END

IF(LCZ1.country_id = 2)
BEGIN
AND
     LCZ1.country_id is not null
END

But it seems to be wrong, it go into error.

What is wrong? What am I missing? How can I fix this issue?

标签: mysqlsqldatabaserdbms

解决方案


希望这对你有用。不要介意我已经声明了一个变量。将其替换为您的列。

DECLARE @LCZ2.country_id varchar(20)
set @LCZ2.country_id=(SELECT LCZ2.country_id FROM Localization AS LCZ2 WHERE LCZ2.id = 5))
IF(@LCZ2.country_id= 1)
BEGIN
   set @LCZ2.country_id= 'not null'
END
IF(@LCZ2.country_id= 2)
BEGIN
   set @LCZ2.country_id= 'not null'
END

推荐阅读