How to insert data with IGNORE if one variable is

2019-08-16 19:26发布

问题:

I would like to use INSERT IGNORE INTO in order to enter only data that doesnt exist allready in my database. Now my question is: How can I do this if I have a variable "time" which is allways different. But the rest would be the same.

For example:

"INSERT IGNORE INTO something (value1, value2, time)
VALUES ('".$value1."', '".$value2."', '".NOW()."')"

How could I tell INSERT IGNORE that he should insert all data even though the time (NOW()) is allways different?

Thanks for your help!

回答1:

INSERT IGNORE would skip an insert only if a unique key is violated (not if all columns are the same). Define a unique key which includes all relevant columns, and does not include the time column.

Example: if you already have the record:

1,2,12:00

And a unique key which covers the first and second columns, running

INSERT IGNORE INTO table VALUES(1,2,14:30)

Will not insert the record, while

INSERT IGNORE INTO table VALUES(1,3,14:30)

Will insert a new record.



回答2:

You need to add a primary key to avoid the duplication of records

alter table something add primary key (value1,value2,time);


标签: php mysql insert