0

How add foreign key in existing table

ALTER TABLE retailer_commission ADD FOREIGN KEY (Retailer_Id) REFERENCES retailer(Id)

enter image description here

dev1
  • 231
  • 2
  • 5
  • 12

2 Answers2

0

Since the types of the Retailer_id column in the retailer_commission table and the Id column in the retailer table are both the same type (int(11)), there must be another explanation for your error.

One likely explanation is that the retailer_commission table has records with Retailer_id values which refer to records in retailer which do not exist.

If the following query gives you a non empty set, the records returned should be considered as problematical:

SELECT rc.*
FROM retailer_commission rc LEFT JOIN retailer r
    ON rc.Retailer_id = r.Id
WHERE r.Id IS NULL
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I am using this query,Query working fine result has been display.New error has display "#1452 - Cannot add or update a child row: a foreign key constraint fails (`testdatabase`.`#sql-15c0_dc`, CONSTRAINT " – dev1 Mar 28 '16 at 06:06
0

Problem has been resolved,In foreign key table there is lot of records that is the reason to occurred this error,I have truncate this table(Foreign table) then execute "ALTER TABLE retailer_commission ADD FOREIGN KEY (Retailer_Id) REFERENCES retailer(Id)",Query has been successfully done.

dev1
  • 231
  • 2
  • 5
  • 12