PHP MYSQL 如果存在则更新,如果不存在则插入?
我不知道这是否正确。我有一个类,如果字段当前存在,我想更新数据库,如果不存在则插入。复杂的是我正在做一个连接 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;
}
I have no idea if this is even remotely correct. I have a class where I would like to update the database if the fields currently exist or insert if they do not. The complication is that I am doing a joining 3 tables (set_colors, school_art, baseimage)
Any help would be really great.
Here is what I have:
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信您正在寻找以下语法:
MySQL 文档:
INSERT ... ON DUPLICATE KEY更新语句
I believe you are looking for the following syntax:
MySQL Documentation:
INSERT ... ON DUPLICATE KEY UPDATE Statement
两种选择:
MySQL 手册:: INSERT INTO ... ON DUPLICATE KEY UPDATE 语法
或
MySQL 手册:: REPLACE INTO 语法
两者都允许您在一个查询中执行 insert-if-not-exists-or-update 操作。
Two choices:
MySQL Manual :: INSERT INTO ... ON DUPLICATE KEY UPDATE Syntax
or
MySQL Manual :: REPLACE INTO Syntax
Both will allow you to do the insert-if-not-exists-or-update in one query.