Nuvolari
Nuvolari

Reputation: 1155

Query With Conditional If Statement

I am trying to write a query that would select another row if the first one is not found ie grab a 'default' if it can't find the one specified.

Something similar to this:

SELECT
*
FROM
teams
WHERE
team=:team_id
ELSE
WHERE team=1

Is this possible to do in Mysql?

BTW the default could be anything not just 1.

Upvotes: 1

Views: 86

Answers (3)

Nuvolari
Nuvolari

Reputation: 1155

Having looked at my question again I've thought maybe its easier to do then I originally thought.

Would the following not work?:

SELECT
*
FROM
teams
WHERE
team=:team OR (team!=:team AND team=:default_team)

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382150

supposing :team_id is greater than 1 you could do

select * from teams where team=1 or team=:team_id order by team desc limit 1

or if you don't know the order of both id :

select * from teams where team=1 or team=:team_id order by team=:team_id desc limit 1

Upvotes: 2

fthiella
fthiella

Reputation: 49049

SELECT * FROM teams WHERE team=:team_id
UNION ALL
SELECT * FROM teams WHERE team=1
ORDER BY team=1
LIMIT 1

Upvotes: 2

Related Questions