简体   繁体   English

仅将数据从一个表插入到另一个表中

[英]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. 我有以下MySQLi代码,用于将列数据从一个表插入到另一个表,这绝对正常。 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. 但是,我希望它仅在check_in表中不存在列数据时才插入列数据。 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: 您可以使用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]);

You can use NOT EXISTS like this : 您可以像这样使用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();

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 有关更多信息: http : //dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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