开发者

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 progra开发者_StackOverflow中文版m 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(i.e. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜