簡體   English   中英

為什么查詢不會因子查詢中不存在的列而失敗?

[英]Why query does not fail with nonexistent column in subquery?

我在查詢中拼寫錯誤並面臨 MySQL 的奇怪行為。

create table aaa (id bigint auto_increment primary key, 
                  amount int not null, 
                  other_column varchar(20)) engine=InnoDB
create table bbb (aaa_id bigint not null, 
                  comment varchar(200), 
                  key(aaa_id)) engine=InnoDB; 
insert into aaa(other_column, amount) values ('hello, world', 12), 
                                             ('second string', 15), 
                                             ('one more', 100);
insert into bbb value (2, 'no 2s!');

以下查詢產生null結果(我輸入了“id”而不是“aaa_id”):

select sum(amount) from aaa where id not in (select id from bbb);

“也許 'id' 對 MySQL 有特殊意義”,我想。 但是,以下查詢正常執行並返回127 (就像子查詢返回空結果一樣):

select sum(amount) from aaa where id not in (select other_column from bbb);

以下查詢產生預期結果:第一個失敗, Unknown column 'id2' in 'field list'第二個返回112

select sum(amount) from aaa where id not in (select id2 from bbb);
select sum(amount) from aaa where id not in (select aaa_id from bbb);

可以看出,如果列存在於外部查詢中,MySQL 會以某種方式執行子查詢。 但是子查詢中這些列的含義是什么?

在 5.1.70 和 5.5 上測試。

這個查詢:

select sum(amount)
from aaa
where id not in (select id from bbb);

解釋為:

select sum(aaa.amount)
from aaa
where aaa.id not in (select aaa.id from bbb);

因為bbb.id不存在。 在編寫 SQL 時,我建議您始終使用表別名。 您認為您正在編寫的查詢:

select sum(aaa.amount)
from aaa
where aaa.id not in (select bbb.id from bbb);

會產生你期望的錯誤。

如果您像這樣創建了bbb表:

create table bbb (aaa_id bigint not null, 
                  ^^^^^^

你為什么要使用

select sum(amount) from aaa where id not in (select id from bbb);
                                                    ^^

然后呢? DB 不是心靈感應的,它無法讀懂你的想法。 如果您告訴它在表中使用字段x ,那么它將需要x實際存在,並且不會隨機選擇一些其他字段。

子查詢可以“伸出手”並從外部/父查詢中獲取字段名稱,如果告訴數據庫這樣做,例如

SELECT id
FROM aaa
WHERE 
   id in (SELECT ... FROM bbb WHERE aaa.id = bbb.somefield)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM