As I said in the comments, I reluctantly will show how a unique key can be used in a de-normalized fashion, and the OP wanted to see it.
The concept is that you know the users, so have them wedged in the battles table. How you then proceed on to a battle_users
table is up to you and I would recommend no change there.
create table battlesA1
( id int auto_increment primary key,
createDt datetime not null,
user1 int not null,
user2 int not null,
-- FK Constraints go here (not shown, FK to users table)
-- Then unique constraint goes here
unique key(user1,user2) -- user1 is less than user2 on insert
-- so on insert, utilize the least() and greatest() functions (mysql)
-- or your front-end programming language
);
insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00',1,2);
-- success
insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00',1,2);
-- Error 1062, Duplicate Entry
least()
and greatest()
examples:
set @user1:=14;
set @user2:=7;
insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00', least(@user1,@user2), greatest(@user1,@user2) );
-- success
insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00', least(@user1,@user2), greatest(@user1,@user2) );
-- Error 1062, Duplicate Entry
set @user1:=6;
set @user2:=700;
insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00', least(@user1,@user2), greatest(@user1,@user2) );
-- success
insert battlesA1(createDt,user1,user2) values ('2016-06-14 12:30:00', least(@user1,@user2), greatest(@user1,@user2) );
-- Error 1062, Duplicate Entry
drop table battlesA1; -- perhaps the best command you see here.
Manual pages for least(), greatest() and LAST_INSERT_ID(). The latter was not used but is used often in cases like this.
So there you have it. You wanted to see it, and I am not terribly proud to show it.