I am trying to prevent duplicate entries like this
INSERT IGNORE INTO myTable( `val_1`, `val_2`, `val_3`, `date` )
VALUES ( '$var_1', '$var_2', '$var_3', now() )
The values i would like to check are the 3 val_x
but because now()
will be a unique value, insert ignore does not work.
How can i not check that last variable as unique?
note: this is kind of like a cart, so i cannot make the first 3 values unique. There is a session variable that allows each user to see aa unique collection.
From this diagram, the first 2 rows are duplicate since they belong to the same user session. The 3rd row is not a duplicate becase it belongs to a different user session
+---------+-------+--------+
| session | var 1 | var 2 |
+---------+-------+--------+
| abc1234 | aaaaa | bbbbb |
+---------+-------+--------+
| abc1234 | aaaaa | bbbbb |
+---------+-------+--------+
| 5678def | aaaaa | bbbbb |
+---------+-------+--------+
| 5678def | aaaaa | ccccc |
+---------+-------+--------+
as paqogomez suggested i removed now()
from the query and altered the table but it looks like i need a primary key for insert ignore
to work, but for my scenario i cant make these 3 columns unique
ERROR 1062: Duplicate entry 'aaaaa' for key 'var 1'
Create a unique index on the first three columns:
create unique index myTable_session_val2_val3 on myTable(session, val_1, val_2);
This will guarantee that combinations of these three are unique, without taking into account any other columns.
I would suggest moving the date into the default value of the column.
ALTER TABLE mytable CHANGE `date` `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
This way, you can still deal with the duplicates in the data in PHP. The alternative, as others have suggested would result in a database foreign key error if you attempted to insert a duplicate.
Then this sql would work and give the same result:
INSERT IGNORE INTO myTable( `val_1`, `val_2`, `val_3` )
VALUES ( '$var_1', '$var_2', '$var_3' )
EDIT:
You still need a unique index to make it work. See @Gordon's answer
You should probably define the UNIQUE
keys for the combination of columns you don't want to be duplicated. So, don't specify column date as UNIQUE
. Did you verify that? Define rest of three values as unique columns. It will probably work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.