Insert unique values โ€‹โ€‹from PHP array into SQL table

Possible duplicate:
How to "paste if does not exist" in MySQL?

There is an 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 arrays of PHP arr1[]=array("abc","bcd")and arr2[]=array("abc","cde").

Say I saved the values โ€‹โ€‹of arr1 [] in an SQL table. Suppose now that I need to store the values โ€‹โ€‹of arr2 [] in the same SQL table. What SQL INSERT query should I write to avoid duplicating the saving of the "abc" record? The result should be:

MyTable:
1  |  abc
2  |  bcd
3  |  cde

but NOT:

MyTable:
1  |  abc
2  |  bcd
3  |  abc
4  |  cde

UPDATE: Maybe MyTable should be created / defined so that duplicate entries are ignored?

+5
source share
3 answers

Do MyVaras UNIQUEin 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`)
);

, , ,

ALTER TABLE `request`
ADD UNIQUE INDEX `myvaridx` (`MyVar`)
+1

3 : INSERT IGNORE, REPLACE INSERT ... ON DUPLICATE KEY UPDATE. .

-, , .

+6

SQL .

"array_merge" , "array_unique" .

.

0

All Articles