简体   繁体   中英

Insert rows only when id from another table exists

My program gets a list of IDs, some of which are in our system, some of which are not. The goal is to make a entry into a table for the IDs which exist in our system but ignore those which do not.

Example:

Incomming    My System    Inserted
555          583          583
583
599

My initial thought was to use INSERT IGNORE but the list of ID's to check against are in the users table, and the rows are being inserted to the events table. I also tried a Foreign Key constraint but INSERT IGNORE doesn't fail silently with a FK - it produces an error which kills any following inserts.

My current angle of attack is to read in all the IDs from the users table to PHP, and check the IDs in PHP before attempting to insert, but this seems sub-optimal. Is there a MySQL way to do it?

INSERT INTO your_id_table (ID) 
SELECT ID FROM my_system_table WHERE ID IN (list_of_ids)

I hope its clear, with this you don't have to do any check at all, you just run the query and be done with it.

You could use an if exists() statement that checks if the value exists in user table before inserting.

if exists (select * from user where id = @id)
begin
     /*insert*/
end
else
begin
    /*return a status message or insert in error table to track failed records*/
end

This is a pretty ugly way to do it, but it works:

$ids = array( /* ids */ );
$ids = implode(',', $ids);
$sql = 'SELECT `id` FROM `table` WHERE `id` IN ('.$ids.')';

$result = $db -> query($sql);
$exists = $result -> fetch_all();
$doesntExist = array_diff($ids, $exists);

You could try:

INSERT INTO Inserted(id) VALUES SELECT id FROM Incoming WHERE id IN (SELECT id FROM My_System)

This selects the id's in Incomming that are also in My_System and inserts those into Inserted.

You can make something like this:

INSERT INTO events (iduser)
SELECT iduser
FROM users WHERE iduser IN (1,2,3,4,5)

This query is only going to return the user id's that are present on the table, so this should do the trick.

If you have more columns to insert, it would go something like this:

$idsToInsert = "1,2,3,4,5,6";
$query = "INSERT INTO events (iduser, title)
SELECT iduser, ".$title."
FROM users WHERE iduser IN (".$idsToInsert.")";

And don't forget to sanitize your input, using mysql_real_escape, you can also use parameterized query s to accomplish this.

That last part of the query you have to generate dynamically trough PHP, but that isn't a problem

Mysql Reference for the insert into table select from is here: http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

You can do this on PHP Code

$result = mysql_query("SELECT id FROM another_table WHERE id = '100'");
$number_of_rows = mysql_num_rows($result);
if ($number_of_rows > 0) {
// ID exist in other table
}

FK produces an error which kills any following inserts

Why does that kill following inserts? Make inserts one by one, try - catch mysql errors.

This is the most elegant solution I can think of:

INSERT INTO events (id)
SELECT id FROM my_system ms
LEFT JOIN incoming i 
ON i.id = ms.id
WHERE i.id IS NOT NULL

The idea here is you exclude those records in the Incoming table which don't have a matching record in the my_system table, because the result set will be null for the Incoming IDs.

Looks like some other people have already come up with a similar solution! Hope this helps, anyways.

An inner join is the cleaniest way to pull it off

INSERT INTO events (id) 
SELECT incoming.id
FROM my_system ms 
INNER JOIN incoming i  
USING (id);

Just load the incoming ids into the incoming table. Also, remember to have id as the PRIMARY KEY of both tables.

Just do:

insert into events (id, value1, value2, ...)
select id, @value1, @value2, ...
from users
where id = @id

This way it will insert only if the id already exists in your users table. This assumes the id value is unique for each row in the users table, but if it weren't just add distinct after select to ensure only one row is inserted.

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