Why query does not fail with nonexistent column in subquery?

后端 未结 2 1662
栀梦
栀梦 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:49

    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)
    

提交回复
热议问题