I have a sql like that:
Select xxx, yyy, zzz,...
FROM
Table1, Table2
WHERE
Table1.Id = Table2.Table1Id
If(Table1.Id = 0) then
AND Table1.Id = 2
How to write this if condition in this case? I tried expand inline but there is a injection warning appear. What is the best way?
@Minh Quang Nguyen
In SQL, you can use a CASE statement within the WHERE clause to conditionally filter data. However, the CASE statement itself can't be used to conditionally apply AND conditions in the WHERE clause.Instead, you can use logical operators to construct your condition in a way that produces the desired effect. Here's how you could rewrite your SQL query to include the conditional logic:sqlCopy codeSELECT xxx, yyy, zzz, ...FROM Table1, Table2WHERE Table1.Id = Table2.Table1IdAND ( (Table1.Id != 0) OR (Table1.Id = 0 AND Table1.Id = 2))This SQL query will join Table1 and Table2 on Id and Table1Id, respectively. It will also apply the following conditions:If Table1.Id is not equal to 0, the record will be included.If Table1.Id is equal to 0, it will also check that Table1.Id is equal to 2 (which is impossible, effectively filtering out records where Table1.Id is 0).The logical condition is designed to handle your specific use case, as you described it.
Hope this helps.Best,RAD Manage
In SQL, you cannot use an IF statement directly in your WHERE clause the way you've tried. You can use a CASE statement instead as RAD shows, or structure your WHERE clause to handle the condition you're dealing with.
If you want to include a condition where if Table1.Id is 0, then you only want rows where Table1.Id is 2, you can use a logical OR in your WHERE clause to make this happen > like this:
SELECT xxx, yyy, zzz,...
FROM Table1
JOIN Table2 ON Table1.Id = Table2.Table1Id
WHERE (Table1.Id <> 0 OR Table1.Id = 2)