schwim;11007351 wrote:Is there a way to check for the presence of the id in one table and the absence of the same id in another table all in one query
Yes; you could use a join or a subquery. I'd probably use the latter, so that's the example I'll give:
SELECT
user_id, col1, col2
FROM
table1
WHERE
user_id NOT IN (
SELECT user_id FROM table2
)
In other words, the subquery collects all of the user_id values from table2, and the outer query will then only SELECT the rows form table1 having a user_id value that doesn't appear in table2.
EDIT: Just for completeness (and since I'm on my lunch break), I'll throw in a JOIN example as well:
SELECT
t1.user_id, t1.col1, t1.col2, t2.user_id
FROM
table1 t1
LEFT JOIN t2 ON t1.user_id = t2.user_id
WHERE
t2.user_id IS NULL
The end result is the same, but you're going about it a bit differently; the LEFT JOIN ensures that all records in table1 get SELECT'ed, meaning the t2.user_id will be set to the NULL value if the JOIN condition can't be satisfied (e.g. there is no matching row in table2). You then utilize that fact in the WHERE clause by eliminating the rows from the combined result set that did satisfy the JOIN condition (e.g. there was a matching row in table2), leaving you with only the rows in table1 that couldn't be JOIN'ed with any from table2.
schwim;11007351 wrote:is this an efficient enough method of handling the situation?
Definitely not. Any time you see a SQL query being executed in a loop (especially inside of a loop that's processing the results of another SQL query), giant red flags should pop up as it's likely very inefficient. SQL is perfectly capable of handling related sets of data (hint: it's one of the primary reasons to be using it in the first place), but by manually doing the operations/comparisons yourself inside the application, you're tying the DBMS' hands and forcing it to be no smarter (and equally or less efficient) than a flat file parser.