如何正确使用 IF 语句添加特定的 WHERE 条件?
How to correctly use an IF statment to add a specific WHERE condition?
我不太喜欢数据库,我在处理涉及 IF 语句的 MySql 查询时遇到问题.
我有这个小查询(工作正常):
(LCZ1.country_id = (SELECT LCZ2.country_id FROM Localization AS LCZ2 WHERE LCZ2.id = 5))
即return一个整数值(1或2)转化为LCZ1.country_id.
如果 returned 值为 1,我想使用 IF 语句做某事,如果它是 2,我想做其他事。
我正在尝试做这样的事情(这个 IF 语句应该在 WHERE 子句中添加一个 AND 条件):
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
但是好像不对,报错了
怎么了?我错过了什么?我该如何解决这个问题?
希望这对您有用。不要介意我已经声明了一个变量。将其替换为您的专栏。
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
尝试下面提到的查询
SELECT case
when LCZ2.country_id is null then 'null'
when LCZ2.country_id = 1 then 'something1'
when LCZ2.country_id = 2 then 'something2'
end as output
FROM Localization AS LCZ2
WHERE LCZ2.id = 5;
注:1. LCZ2.id不为空
2. 在 something1, something2 和 null
中随意更改
我不太喜欢数据库,我在处理涉及 IF 语句的 MySql 查询时遇到问题.
我有这个小查询(工作正常):
(LCZ1.country_id = (SELECT LCZ2.country_id FROM Localization AS LCZ2 WHERE LCZ2.id = 5))
即return一个整数值(1或2)转化为LCZ1.country_id.
如果 returned 值为 1,我想使用 IF 语句做某事,如果它是 2,我想做其他事。
我正在尝试做这样的事情(这个 IF 语句应该在 WHERE 子句中添加一个 AND 条件):
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
但是好像不对,报错了
怎么了?我错过了什么?我该如何解决这个问题?
希望这对您有用。不要介意我已经声明了一个变量。将其替换为您的专栏。
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
尝试下面提到的查询
SELECT case
when LCZ2.country_id is null then 'null'
when LCZ2.country_id = 1 then 'something1'
when LCZ2.country_id = 2 then 'something2'
end as output
FROM Localization AS LCZ2
WHERE LCZ2.id = 5;
注:1. LCZ2.id不为空 2. 在 something1, something2 和 null
中随意更改