我有以下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();
我怎样才能做到这一点?
最佳答案
您可以这样使用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();