alex_unio
alex_unio

Reputation: 325

SQL Different query depending on the if result

I want to do a query that depending on the char_length of one parameter should select one table or another. It should be something like this but I know that is not correct at all and there are syntax errors which I can't find.

SELECT IF (
CHAR_LENGTH('var44') < 3,
name FROM nets WHERE code = 'var44',
name FROM variable WHERE id = (SELECT SUBSTRING('var44',4)) 
);

Any ideas? Thanks.

Upvotes: 0

Views: 44

Answers (2)

Leonard Pauli
Leonard Pauli

Reputation: 2693

As GhostGambler said, why not do this with php?

if (strlen($var44)<3) {
    $sql = mysql_query("SELECT name FROM nets WHERE code = '$var44'");
} else {
    $var44 = substring($var44, 4);
    $sql = mysql_query("SELECT name FROM variable WHERE id = '$var44'");
}

Upvotes: 0

wumpz
wumpz

Reputation: 9201

Would that be a solution for you:

select name from nets WHERE code = 'var44' and CHAR_LENGTH('var44') < 3
union
select name FROM variable WHERE id = (SELECT SUBSTRING('var44',4)) and CHAR_LENGTH('var44') >= 3

or is the if statement forced?

Upvotes: 1

Related Questions