Prat
Prat

Reputation: 529

How to avoid duplicate data into Mysql table?

order-:

order_id(PK)    item     status  order_no
1               pant        0       100
2               shirt       1       200  

product-:

   prod_id(Fk)    id(pk)   price     quantity   order_no  status
   1               1         10          2          100        0
   1               2         20          3          100        0   
   2               3         15          1          200        1

These are my two table-: order & product.

what happend is to insert data into product table, my query first check status of order table & if it is 0, it add data into product table.

My program runs through CRON job..so each time it just checks order status & if it is 0, it again adds same data into product table.

i.e. my product table become like this

 prod_id(Fk)    id(pk)   price     quantity   order_no  status
   1               1         10          2          100        0
   1               2         20          3          100        0   
   2               3         15          1          200        1
   1               4         10          2          100        0
   1               5         20          3          100        0   

which I don't want. my id column is pk which is auto-incremented... so how should I avoid duplicate data into Product table?

Is there any way we can update or replace the same data??

plz guide me..

Upvotes: 0

Views: 699

Answers (1)

eggyal
eggyal

Reputation: 126035

Create a UNIQUE index on prod_id (or whatever columns determine that the record is to be updated rather than inserted), and then use either INSERT ... ON DUPLICATE KEY UPDATE or REPLACE.

Upvotes: 3

Related Questions