Mysql duplicate foreign key constraint

后端 未结 1 1561
悲&欢浪女
悲&欢浪女 2021-01-19 04:17

When I try to import a database I get this error

SQL query:
ALTER TABLE `bid`
ADD CONSTRAINT `bid_ibfk_4` FOREIGN KEY (`auction_contact_id`) REFERENCES `auct         


        
相关标签:
1条回答
  • 2021-01-19 05:04

    If you look at the result of your query, the foreign key bid_ibfk_3 already exists. In fact it is in the second row of the result.

    def     projekt_classics    bid_ibfk_2      projekt_classics    bid     FOREIGN KEY
    --the row below is the foreign key that you are trying to create
    def     projekt_classics    bid_ibfk_3      projekt_classics    bid     FOREIGN KEY
    def     projekt_classics    car_ibfk_1      projekt_classics    car     FOREIGN KEY
    def     projekt_classics    car_ibfk_3      projekt_classics    car     FOREIGN KEY
    def     projekt_classics    car_ibfk_4      projekt_classics    car     FOREIGN KEY
    def     projekt_classics    car_brand_ibfk_1    projekt_classics    car_brand   FOREIGN KEY
    

    That's why you are getting the duplicate foreign key constraint name when you are trying to execute this:

    ADD CONSTRAINT `bid_ibfk_3` FOREIGN KEY (`car_id`) REFERENCES `car` (`car_id`)
    

    You can modify your query to check first if the foreign key that you are trying to create does not exist, before actually creating it.

    IF NOT EXISTS (SELECT NULL FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
                       WHERE CONSTRAINT_SCHEMA = DATABASE()
                             AND CONSTRAINT_TYPE = 'FOREIGN KEY'
                             AND CONSTRAINT_NAME = 'bid_ibfk_3') THEN
       ALTER TABLE `bid` ADD CONSTRAINT `bid_ibfk_3`
            FOREIGN KEY (`car_id`) REFERENCES `car` (`car_id`);
    END IF
    
    0 讨论(0)
提交回复
热议问题