search

Home  >  Q&A  >  body text

How does mysql determine if the data does not exist and then insert it?

When inserting data, can we combine the following requirements into one sql statement?

1, determine whether the data exists;

2, there is no insertion;

3, then query the id field value of the data

怪我咯怪我咯2742 days ago984

reply all(4)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-07-04 13:45:40

    Probably not possible, you have to do two queries separately, one query and one insert. Unless you call a stored procedure. The stored procedure should be able to achieve your needs

    reply
    0
  • 阿神

    阿神2017-07-04 13:45:40

    Use insert if not exists

    INSERT INTO table(field1, field2, fieldn) SELECT 'field1', 'field2', 'fieldn' FROM DUAL WHERE NOT EXISTS(SELECT field FROM table WHERE field = ?)

    reply
    0
  • 怪我咯

    怪我咯2017-07-04 13:45:40

    MySQL, please use the powerful REPLACE INTO

    reply
    0
  • 世界只因有你

    世界只因有你2017-07-04 13:45:40

    Mysql can use REPLACE INTO, but it must have a unique index as a condition, but I have not used this, I feel it is more reliable to do it step by step

    reply
    0
  • Cancelreply