Reputation: 2135
How can I return multiple values from an IF statement in MySQL? Embedding the IF into the query is not an option.
SET @values = IF(@year = 2014, (2, 3, 4), 1); # either (2, 3, 4) OR 1
SELECT * FROM whatever WHERE `column` IN (@values);
Error Code: 1241. Operand should contain 1 column(s)
One solution would be to use quotation marks and store that value to a variable, but it does not work with the IN command, it needs raw numbers:
SELECT IF (24 IN ("23,24,25"), TRUE, FALSE) AS `does-it-contain`;
FALSE
Upvotes: 1
Views: 2480
Reputation: 780724
If you're doing this in a procedure (either a MySQL stored procedure or from a client programming language) you can use a temporary table.
CREATE TEMPORARY TABLE temp_values (value INT, PRIMARY KEY value);
IF @year = 2014
THEN INSERT INTO temp_values VALUES (2), (3), (4);
ELSE INSERT INTO temp_values VALUES (1);
END IF;
SELECT w.* FROM wherever AS w
JOIN temp_values AS v ON v.column = v.value;
Upvotes: 1