views:

331

answers:

3

I am busy doing an UPDATE/INSERT request, but here is the crux:

table PLAYERS {
    player_id
    game_id
    team_id
    position
    number
}

What is supposed to happen is the following:

I test if there is an entry where player_id = '$player_id' AND game_id = '$game_id' AND team_id = '$team_id'.

If there is, then the following happens:

position = '$position' AND number = '$number'

Is there any way I can do this using just MySQL query language, without the need for PHP validation between queries?

+5  A: 
INSERT INTO TABLE (COLUMNS) VALUES(FIELDS) UPDATE ON DUPLICATE KEY position = somevalue, number=number

1) Tries to Insert
2) If there is a record with a unique field (Primary Key, Unique Index, etc) update that field instead.

Chacha102
This is my query:`INSERT INTO players (game_id,player_id,position,number) VALUES('$game_id','$players[$i]','$position[$i]','$number') UPDATE ON DUPLICATE KEY position = '$position[$i]', number='$number'`But I get the following error:`You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE ON DUPLICATE KEY position = 'LH Prop', number='1'' at line 1`Any ideas?
Anriëtte Combrink
Yes you have errors. You are inputing numbers as strings :)
Havenard
I have been inserting like this the whole time, and it worked.
Anriëtte Combrink
I think it should be "ON DUPLICATE KEY UPDATE"
Zed
Yes, thanks Zed, I changed it to that and then it processed, but I think my problem is the fact that I don't have any PRIMARY KEY, except INDEXES on game_id, player_id and team_id. So it processes the request, but keeps on inserting new entries, but in fact, the new entries are precise duplicates of other entries in the table.Anyone else have some direction for me?
Anriëtte Combrink
The INDEXES are NON-UNIQUE
Anriëtte Combrink
`ALTER TABLE PLAYERS ADD PRIMARY KEY (player_id, game_id, team_id);`
searlea
Shouldn't field identifiers be quoted with `` ?
dotty
A: 

Well, I fixed this with multiple IF-statements to determine whether to insert or to update.

Anriëtte Combrink
A: 

That will not work unless its in a transaction, or you can guarantee that simultaneous requests against the DB will not be run

HaveAGuess