Forum Moderators: coopster
I have 2 tables (table1 and table2) that contain a list of usernames. I need to delete the records in table2 that appear in table1. Eg: If foo appears in table1 and table2, the entry needs to be deleted in table2.
I currently use the following code, that gets the usernames from table1 and deletes the entries from table2. However, I'm not sure if this is the best optimised way of working with tables containing 50,000 entries+. Also, the script below will attempt to delete the username even if it does not exist in table2...
Are there better methods of accomplishing this?
<?php
// Get the records from table1
$sql =
("
SELECT
username
FROM
table1
");
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc ($result))
{
$username = $row['username'];
// Delete the username in table2
$sqldelete =
("
DELETE
FROM
table2
WHERE
username = '$username'
");
$sqldeleteResult = mysql_query($sqldelete);
}
?>
TIA
$query = "DELETE FROM table2 WHERE table2.colname = (SELECT colname FROM table1 WHERE colname = table2.colname)";
Hope this helps some. :)
Good luck!
// get the rows from table1
$q = "SELECT id FROM table1";
while ($r = mysql_fetch_array(mysql_query($q),MYSQL_ASSOC))!== false) {
// check the ids in table2
$q2 = "SELECT id FROM table2 WHERE id = '".$r['id']."'";
while ($r2 = mysql_fetch_array(mysql_query($q),MYSQL_ASSOC))!== false) {
// delete them
mysql_query("DELETE FROM table2 WHERE id = '".$r2['id']."'");
}
}
That should do the trick!
IE:
table_1 (
t1_id
stuff1
stuff2
etc...
)
table_2 (
t1_id
stuff...
foreign key( t1_id ) references table_1( t1_id )
on delete cascade
);
Or something similar to that...
Paul.