Jimbu
Jimbu

Reputation: 17

Are ELSE IF statements possible?

Hello I am new to MySQL and PHP and was just wondering if this was MySQL query were valid:

IF (NOT EXISTS(SELECT uid2 FROM table WHERE uid1 = '$uid1'))
BEGIN
    UPDATE table
    SET uid2 = $var
END
ELSE
IF (NOT EXISTS(SELECT uid3 FROM table WHERE uid1 = '$uid1'))
BEGIN
    UPDATE table 
    SET uid3 = $var
END

I am attempting to insert $var into my table but only if there is no value for uid2 and uid3. Hopefully this makes sense I've been getting a lot of down votes and don't know why :/

Upvotes: 1

Views: 60

Answers (2)

Rana Aalamgeer
Rana Aalamgeer

Reputation: 712

When we use EXISTS or NOT EXISTS statements in mysql the subquery always starts with select * statement as below.

NOT EXISTS(SELECT * FROM table WHERE uid1 = '$uid1')

Try it.

IF (NOT EXISTS(SELECT * FROM table WHERE uid1 = '$uid1'))
BEGIN
    UPDATE table
    SET uid2 = $var
END
ELSE
IF (NOT EXISTS(SELECT * FROM table WHERE uid1 = '$uid1'))
BEGIN
    UPDATE table 
    SET uid3 = $var
END

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521609

I think you can reduce this to a single query without using IF:

UPDATE table
SET uid2 = $var,
    uid3 = $var
WHERE NOT EXISTS (SELECT * FROM table WHERE uid1 = '$uid1')

Your two NOT EXISTS conditions are logically the same as far as I know.

Upvotes: 2

Related Questions