I misspelled in my query and faced with MySQL\'s strange behaviour.
create table aaa (id bigint auto_increment primary key,
amount int not nul
This query:
select sum(amount)
from aaa
where id not in (select id from bbb);
Is interpreted as:
select sum(aaa.amount)
from aaa
where aaa.id not in (select aaa.id from bbb);
because bbb.id
does not exist. When writing SQL, I suggest that you always use table aliases. The query that you thought you were writing:
select sum(aaa.amount)
from aaa
where aaa.id not in (select bbb.id from bbb);
would generate the error you expect.
If you created the bbb
table like this:
create table bbb (aaa_id bigint not null,
^^^^^^
why would you use
select sum(amount) from aaa where id not in (select id from bbb);
^^
then instead? The DB's not telepathic, it can't read your mind. If you tell it to use field x
in a table, then it's going to need x
to actually exist, and won't randomly pick some OTHER field.
The subquery COULD "reach out" and pick up field names from the outer/parent query, if tell the DB to do so, e.g.
SELECT id
FROM aaa
WHERE
id in (SELECT ... FROM bbb WHERE aaa.id = bbb.somefield)