我有以下MySQLi代码,用于将列数据从一个表插入另一个表,这是非常正常的。但是,我希望它只是在check_in表中不存在列数据时插入列数据。我的代码如下:
$insertInvRoom = $db->prepare("INSERT checkin_rooms (checkin_inventory_id, checkin_room_name, checkin_inventory_room_id) SELECT inventory_id, inventory_room_name, inventory_room_id FROM inventory_rooms WHERE inventory_id = ?");
$insertInvRoom->bind_param("i", $inventoryID[$key]);
$insertInvRoom->execute();
$insertInvRoom->close();
我该怎么做?
答案 0 :(得分:2)
您可以使用IF NOT EXISTS
子句,如下所示:
$insertInvRoom = $db->prepare("IF NOT EXISTS (SELECT * FROM checkin_rooms WHERE checkin_inventory_id = ?) INSERT INTO checkin_rooms (checkin_inventory_id, checkin_room_name, checkin_inventory_room_id) SELECT inventory_id, inventory_room_name, inventory_room_id FROM inventory_rooms WHERE inventory_id = ?");
$insertInvRoom->bind_param("i", $inventoryID[$key], $inventoryID[$key]);
答案 1 :(得分:1)
您可以像这样使用NOT EXISTS
:
$insertInvRoom = $db->prepare("INSERT INTO checkin_rooms (checkin_inventory_id, checkin_room_name, checkin_inventory_room_id) SELECT i.inventory_id, i.inventory_room_name, i.inventory_room_id FROM inventory_rooms i WHERE i.inventory_id = ? " +
" AND NOT EXISTS (SELECT * FROM checkin_rooms cr WHERE cr.checkin_inventory_id = i.inventory_id)");
$insertInvRoom->bind_param("i", $inventoryID[$key]);
$insertInvRoom->execute();
$insertInvRoom->close();
答案 2 :(得分:0)
我知道你已经得到了答案,但是如果你感兴趣的话,你可以做一些其他类型的查询来插入数据(如果它不存在),或者如果它存在则更新它。例如:
INSERT INTO my_table (my_column1, my_column2, my_count)
VALUES ('some string', 14, 1)
ON DUPLICATE KEY
UPDATE my_column1 = 'some_string', my_column2 = 14, my_count = my_count + 1;
这次可能对你没有帮助,但是如果你只是想确定行是否在那里,无论它是否已经存在,而且不进行多次查询,它会非常有用。
了解更多信息:http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html