There is a table consists of the following columns: party_name, party_id , party, party2_id , val1, val2

It is necessary that the two values party_id and party2_id were checked when writing if they already exist (exactly two in the same DB line) when attempting to write, then it is necessary to overwrite the "update" data in this line. Separately, party_id and party2_id can be repeated countless times, but together in the same line they can occur only once, but there can be an option when party_id changes places with party2_id for example:

Line number 1 DB party_id = 1 party2_id = 2

Line number 2 DB party_id = 2 party2_id = 1

In MySQL, I’m a complete novice, before (I don’t remember how) I used the "unique" property via phpmyadmin on one of the columns - and this did not allow me to write duplicates in a column - do I need to do the same actions, or do I have to solve it through base?

Request Code:

query =(""INSERT INTO "" + ""allbase ""+""(party_name, party_id, party, party2_id, val1, val2) VALUES (%s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE party_name=VALUES(party_name), party_id=VALUES(party_id), party=VALUES(party), val1=VALUES(val1), val2=VALUES(val2)"") 
  • Done! Thank you very much! - Amaroc

1 answer 1

Your request is correct, it will insert a new entry if it succeeds and will update the existing string if the inserted entry violates any unique constraint.

A uniqueness constraint is either a primary key (primary key) or a unique index (unique index). In one restriction must enter both columns. Based on this, if there is no primary key in the table, or you think that it will not prevent you from inserting / updating correctly, add a unique index:

 CREATE UNIQUE INDEX allbase_ind1 on allbase(party_id,party2_id); 

In your case, the two id fields together fit the definition of the primary key i.e. "uniquely identify the record", in this case, when creating the table (or later), declare the primary key based on these two columns:

 create table allbase(party_id int not null , party2_id int not null, ... прочие колонки.. , primary key(party_id,party2_id) ); 
  • Thank! The first option is perfect! - Amaroc