Possible Duplicate:
How to 'insert if not exists' in MySQL?
There is SQL table:
CREATE TABLE IF NOT EXISTS `MyTable` (
`id` smallint(6) NOT NULL AUTO_INCREMENT,
`MyVar` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`)
)
And there are two PHP arrays arr1[]=array("abc","bcd")
and arr2[]=array("abc","cde")
.
Let's say I have saved arr1[] values to SQL table. Now let's suppose I need to save arr2[] values to the same SQL table. Which SQL INSERT query do I need to write in order to avoid duplicate saving of "abc" entry? The result must be:
MyTable:
1 | abc
2 | bcd
3 | cde
but NOT:
MyTable:
1 | abc
2 | bcd
3 | abc
4 | cde
UPDATE: Maybe the MyTable should be created/defined in such a way that duplicate entries are ignored?
The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.
The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed. Note: The returned array will keep the first array item's key type.
The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);
INSERT DISTINCT Records INTO New Tables In order to copy data from an existing table to a new one, you can use the "INSERT INTO SELECT DISTINCT" pattern. After "INSERT INTO", you specify the target table's name - organizations in the below case.
There are 3 possible solutions: using INSERT IGNORE
, REPLACE
, or INSERT ... ON DUPLICATE KEY UPDATE
. Check this article.
You can also in memory intersect array-s and then insert just unique values if that solution fits for you.
Make the MyVar
as UNIQUE
in your table.
Like this:
CREATE TABLE IF NOT EXISTS `MyTable` (
`id` smallint(6) NOT NULL AUTO_INCREMENT,
`MyVar` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `myvaridx` (`MyVar`)
);
or, if you're unable to recreate the table, alter it using
ALTER TABLE `request`
ADD UNIQUE INDEX `myvaridx` (`MyVar`)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With