Michael Phelps
Michael Phelps

Reputation: 3601

IF -condition ERROR 1241 (21000): Operand should contain 1 column(s)

How to fix ?

 mysql> SELECT  IF(1,(SELECT * FROM zd LIMIT 1 ) ,(SELECT *  FROM zd LIMIT 3) );
ERROR 1241 (21000): Operand should contain 1 column(s)
mysql>

Thank you.

Upvotes: 0

Views: 438

Answers (1)

Chris Middleton
Chris Middleton

Reputation: 5942

The error code is more informative than it may seem at first.

Operand should contain 1 columns

In your example, IF is the operator, while 1, (SELECT * FROM zd LIMIT 1 ), and (SELECT * FROM zd LIMIT 3) are the operands.

The IF statement takes three parameters: a boolean value, a scalar value to return if the boolean is true, and a scalar value to return if the boolean is false.

Your select subqueries each return a row. You must return only a single value, like this:

SELECT IF(1,(SELECT col1_name FROM zd LIMIT 1 ) ,(SELECT col2_name  FROM zd LIMIT 1) )

where you replace col1_name and col2_name with whichever columns you want to get data from.

====

Now that I read your question again, I see that what you're actually trying to do is conditionalize the limit. I would just do that in PHP or whatever language you're querying the database with, if that's possible:

$limit = $bool ? 1 : 3;
$mysql->prepare("SELECT * FROM zd LIMIT $limit");
$mysql->execute();
$result = $mysql->fetch(PDO::FETCH_ASSOC)

I'm not sure there's a way to conditionally set the limit within mysql without variables.

Upvotes: 4

Related Questions