简体   繁体   中英

How do I check if data exists in my SQL table and if it doesn't insert the newer data?

My table is made up of 3 values-

  • long
  • short
  • id

id is an auto increment int value and the rest are text.

My PHP script retrieves the latest version of a program every half an hour and stores it as long in an sql table. What I want is for the php script to check if the value is already in the table(ie there are no new versions). If it isn't I want it to insert the new data. Just to make this clear I am not replacing the value "long". I am merely making a new value of it and 'id' is keeping a record of how many versions there have been.

Use the EXISTS Keyword.

INSERT INTO Table (Col1, Col2, Col3)
Values(?, ?, ?)
WHERE NOT EXISTS (
SELECT Col1 FROM TABLE
WHERE Col1 = ? AND Col2 = ? AND Col3 =?)

You can work out which columns you actually need to test.

You can put a UNIQUE index on the long column and use INSERT IGNORE :

INSERT IGNORE INTO versions (long, short)
VALUES (?, ?)

If the key already exists MySQL will generate a warning (not an error) and will neither insert nor update any rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM