how avoid dublicate data to mysql

后端 未结 3 1338
眼角桃花
眼角桃花 2021-01-28 11:27

I write the code to scrap car info(title, make, model, transmission, year, price) data from ebay.com and save in the mysql, I want if all row\'s(title, make, model, ...) item\'s

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-28 12:11

    One option uses not exists:

    insert into car_info (title, maker, model, transmission, year, price) 
    select v.*
    from (select %s title, %s maker, %s model, %s transmission, %s year, %s price) v
    where not exists (
        select 1
        from car_info c
        where 
            (c.title, c.maker, c.model, c.transmission, c.year, c.price)
             = (v.title, v.maker, v.model, v.transmission, v.year, v.price)
    );
    

    But it would be simpler to create a unique key on all columns of the table, like:

    create unique index idx_car_info_uniq
        on car_info(title, maker, model, transmission, year, price); 
    

    This prevents any process from inserting duplicates in the table. You can elegantly ignore the erros that would otherwise have been raised with the on duplicate key syntax:

    insert into car_info (title, maker, model, transmission, year, price) 
    values (%s, %s, %s, %s, %s, %s)
    on duplicate key update title = values(title);
    

提交回复
热议问题