简体   繁体   中英

Insert data from one table to another only if it doesn't already exist

I have the following MySQLi code for inserting column data from one table to another which is working absolutely fine. However what I would like it to do is to insert the column data only if it doesn't already exist in the check_in table. My code is as follows:

$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();

How can I do this?

You can use the IF NOT EXISTS clause, like this:

$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]);

You can use NOT EXISTS like this :

$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();

I know you've already got your answer, but just in case you're interested, there's another type of query you can do to insert data if it doesn't exist, or update it if it does. For example:

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;

Probably doesn't help you this time around, but it's super useful if you just want to make sure the row is there, whether it was already there or not, without doing multiple queries.

For more info: http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM