Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip insert on duplicate entry in mysql

Tags:

sql

php

mysql

I have a favorite table containing some fields like login_id,driver_id(One login_id may have many driver_id) . Then I am using bulk update , not having any check the driver_id is exists in table .

Input data will be set of driver ids , I need to skip the insertion of driver id if the same id already be there for relevant login_id . So the new ids will be inserted and others are not

What can I do with mysql , what are all the settings needed in table .

Please advise me

like image 881
Rinto George Avatar asked Mar 29 '12 04:03

Rinto George


People also ask

How can we prevent insertion of duplicate data?

You can prevent duplicate values in a field in an Access table by creating a unique index.

How do I ignore duplicate records in SQL while selecting query?

If you want the query to return only unique rows, use the keyword DISTINCT after SELECT . DISTINCT can be used to fetch unique rows from one or more columns. You need to list the columns after the DISTINCT keyword.


2 Answers

You can use "INSERT IGNORE INTO".it's return updated row count.

INSERT IGNORE INTO favorite(login_id,driver_id) VALUES (login_id,driver_id) (login_id,driver_id).....
like image 183
jeewiya Avatar answered Oct 13 '22 19:10

jeewiya


create a unique key with login_id and driver_id in mysql.

When you try to insert an existing record based on those keys, an error will be thrown. You can then trap this error and proceed as normal.

CREATE UNIQUE INDEX unique
  ON tbl_name (login_id, driver_id)
like image 28
Ben Rowe Avatar answered Oct 13 '22 19:10

Ben Rowe