I have two tables:
+------- IPs ------+ +---- Groups ---+
| Id (Int) | | Id (Int) |
| IP (String) | | Name (String) |
| Comment (String) | | IPs (String) |
+------------------+ +---------------+
The IPs-column of Groups is a comma-separated list of the IPS that this group consists of (The Id of the IP in the IPs-table of course).
I now want to find all IPs that have not yet been grouped -> No reference in any Groups IPs-field.
My idea was to somehow join all the Groups.IPs together and then search for all the IPs.IPs that are not in that list.
I’d really love to get that done completely in SQL (Programmatically is not the problem).
I’m sure there’s some hacky solution to your problem, but if you want to “get that done completely in SQL”, I suggest refactoring your tables to avoid the comma-separated list of Ids. For a list of problems that comma-separated fields attract, I suggest checking out this recent Stack Overflow post:
I suggest a table schema that looks something like this:
Then your query could be as easy as this:
Example:
Result:
The
127.0.0.1IP does not belog to any group.UPDATE:
You can also solve the above by using the “null-self-join” method:
This is normally faster than the previous solution, because it does not use a correlated subquery. The problem with correlated subqueries is that they are executed once for each row in the outer query, and therefore performance suffers when the outer query (
SELECT * FROM ipsin this case) returns many rows.