Sample Header Ad - 728x90

Optimal way to SELECT all rows in a table that are not referenced by a foreign key?

1 vote
1 answer
1732 views
In MySQL I have a table "resources" that represents a list of resources. eg: CREATE TABLE resources ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(100) NOT NULL, ...etc... PRIMARY KEY(id) ) There are about a dozen other tables in the database that have a foreign key referencing resources. eg: CREATE TABLE something ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, resourceId INT UNSIGNED NOT NULL, ...etc... PRIMARY KEY(id), FOREIGN KEY(resourceId) REFERENCES resources(id) ) CREATE TABLE somethingElse ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, resourceId INT UNSIGNED NOT NULL, ...etc... PRIMARY KEY(id), FOREIGN KEY(resourceId) REFERENCES resources(id) ) etc... For housekeeping, I need to periodically delete all of the rows in resources that DO NOT have a reference in any other table. At the same time I also need to clean some things that are outside of the database that these "orphaned" resources refer to. (eg deletion of a corresponding file.) To do this, I start with the following select statement, to select all rows in resources that are not referenced anywhere by a foreign key: select r.id, r.name from resources as r left join something as a on a.resourceId = r.id left join somethingElse as b on b.resourceId = r.id left join someOtherStuff as c on c.resourceId = r.id left join oneMoreExample as d on d.reosurceId = r.id ...etc... where a.resourceId is null and b.resourceId is null and c.resourceId is null and d.resourceId is null ...etc... limit 100; And then I deal with the results accordingly. This works, and currently this query only takes about 3 seconds to run, which tbh isn't bad. But I am worried that so many left joins have the potential to turn into a bit of bottlenck over time. I am wondering: Are there any other ways this query could / should be written, that might be more optimal / performant ?
Asked by user1031947 (139 rep)
Aug 26, 2022, 04:27 AM
Last activity: Jul 8, 2025, 09:04 PM