Forum Moderators: coopster
Delete from thedatabase where field2 and field 3 on somerow have the same values as field2 and field 3 on someotherrow.
I can't figure out how to compare the data from two different rows.
Anyone have any ideas on how I can do this?
Example:
$query = "SELECT id FROM table";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)){
$new_query = "DELETE FROM table WHERE field2 = '$row[field2]' AND field3 = '$row[field3]' AND id <> $row[id]";
if (mysql_query($new_query)) print "Deleted row #$row[id]!<br />";
}
Basically, it grabs all entries from the db, loops through them one at a time searching the db for other rows that have matching field2 and field3. Also, it will not delete the one being used as comparison. I assume you want to keep at least one entry, even when there are dupes.
For safety, I would test the script by printing the $new_query variable first.
$query = "SELECT id FROM table";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)){
$new_query = "DELETE FROM table WHERE field2 = '$row[field2]' AND field3 = '$row[field3]' AND id <> $row[id]";
print $new_query;
}
If you want to be safe and review records before deleting, this should work
SELECT *, count(*) AS rec_count FROM table_in_question GROUP BY field2, field3 HAVING rec_count > 1
That should return rows where those values are the same... I have to test it to see whether it returns all rows with the matching field.
EDIT:
Okay, so it only returns the first row that matches and a count of the number of rows. You'll then have to search for those values in other records and then you'll have your duplicates.
Tom