我不知道这是否是远程正确的。我有一个类,如果当前存在的字段我想更新数据库,如果不存在则插入。复杂的是我正在加入3个表(set_colors,school_art,baseimage)
任何帮助都会非常棒。
这就是我所拥有的:
public function set_layer_colors($value) {
global $db;
$result_array = mysql_query("
IF EXISTS(SELECT * FROM set_colors WHERE school_art_id = '{$value}')
UPDATE set_colors (school_art_id, baseimage_id, sub_folder, layer)
SELECT school_art.id, baseimage.id, baseimage.sub_folder, baseimage.layer
FROM school_art
JOIN baseimage ON baseimage.base_folder = school_art.series_code
WHERE baseimage.image_type = 'B' ORDER BY school_art.id
ELSE
INSERT INTO set_colors (school_art_id, baseimage_id, sub_folder, layer)
SELECT school_art.id, baseimage.id, baseimage.sub_folder, baseimage.layer
FROM school_art
JOIN baseimage ON baseimage.base_folder = school_art.series_code
WHERE baseimage.image_type = 'B' ORDER BY school_art.id
");
return $result_array;
}
提前致谢。
答案 0 :(得分:176)
我相信您正在寻找以下语法
INSERT INTO <table> (field1, field2, field3, ...)
VALUES ('value1', 'value2','value3', ...)
ON DUPLICATE KEY UPDATE
field1='value1', field2='value2', field3='value3', ...
答案 1 :(得分:33)
两种选择:
MySQL Manual :: INSERT INTO ... ON DUPLICATE KEY UPDATE Syntax
或
MySQL Manual :: REPLACE INTO Syntax
两者都允许您在一个查询中执行insert-if-not-exists-or update。