Why query does not fail with nonexistent column in subquery?

后端 未结 2 1664
栀梦
栀梦 2021-01-21 03:15

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         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 03:40

    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.

提交回复
热议问题