I have tables like this:
CheckTable
(id) (user_id)
[0] [403]
UserTable
(id) (username)
[403] [hello]
I want to select only the rows from the UserTable
that do not have the user id row in the CheckTable
I could just select all the users, loop through the rows and then run another query checking if the user_id
is in the UserTable
, but that would be slow.
Is there any MySQL query that could join and select.
1 Answer 1
Is this what you're looking for?
SELECT Whatever FROM UserTable
WHERE UserTable.username NOT IN
(
SELECT CheckTable.user_id FROM CheckTable
);
If this is not suitable, please expand. Possibly with table definitions - (SHOW CREATE TABLE My_Table\G) and some sample data - (INSERT INTO My_Table VALUES(....)), and finally, the result you want with the logic you used to obtain it.
With further research, you might also find this interesting - and also this. As a generic response, substituting NOT EXISTS
for NOT IN
might be the way to go - YMMV.
-
Should probably be
CheckTable.user_id
instead ofCheckTable.id
. On a different note, I've heard it mentioned more than once that in MySQL theLEFT JOIN
+WHERE IS NULL
method for some reason works better than either NOT IN or NOT EXISTS. Somewhat odd, I know. But in any event, if I was suggesting NOT IN, I would also make sure to mention it's behaviour with lists containing NULLs.Andriy M– Andriy M2016年02月15日 20:34:02 +00:00Commented Feb 15, 2016 at 20:34 -
Your point about
NOT NULL
s is well made, but I did include two links to discussions about theNULL
situation. You are also correct about the field name - should beuser_id
instead ofid
- thanks for that (corrected). Maybe a bit strange to haveuser_id
=username
- i.e. anINT
field = aVARCHAR
? No DDL, so who knows?Vérace– Vérace2016年02月15日 20:39:55 +00:00Commented Feb 15, 2016 at 20:39 -
(NOT) IN ( SELECT ... )
used to evaluate the subquery every time -- very inefficient. 5.6 evaluates it once, builds a tmp table, and conjures up an index -- still more complex thanEXISTS
orLEFT JOIN
.Rick James– Rick James2016年02月15日 23:49:50 +00:00Commented Feb 15, 2016 at 23:49
NOT EXISTS
condition. What have you tried so far?