开发者

mysql query help - REPLACE INTO?

I have a PHP file that reads in a CSV file and stores the values into an SQL table.

The SQL table has 4 columns

 id - primary key (just auto incremented integer)
 name - text value of an object name
 type - an integer value representing the type of object
 active - a bool to set if the object is active

The problem is the CSV file doesn't store the id, just the name and type.

I want to do the following and wondered what the best way to do this is with the least amount of queries.

set active to 0 for every entry in the table

For each entry in th开发者_运维问答e CSV
if (name and type already exists in table)
  set active to 1 
else 
   add new entry to the table

return the id for the existing or new entry

any help would be greatly appreciated

Thanks

  • just a note, it's just the mysql queries i'm after, not php code etc...


Assuming you are using mysql:

First you have to create "unique" index on 2 fields: name and type (it's one index not two)

Then insert your data using this query:

INSERT INTO `table` (`name`,`type`,`active`) VALUES ($name,$type,0)
  ON DUPLICATE KEY UPDATE active = 1

In order to get ID you just query it (the smart way - mysql_insert_id() doesn't work with INSERT UPDATE)

SELECT id FROM `table` WHERE `name`= '$name' AND `type` = '$type'
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜