在子查询或视图上的左连接丢失具有空值的行

时间:2018-03-30 05:26:30

标签: sql subquery left-join mariadb

我在视图&上使用了“左连接”。子查询但在mariadb 10.2.11+中丢失了'null'行。我不知道这是怎么发生的。你能解释一下吗?

架构和数据:

create table t1 (
  id int not null auto_increment,
  name varchar(50),
  primary key (id)
) engine = innodb auto_increment = 1 default character set = utf8;
create table t2 (
  id int not null auto_increment,
  pid int not null,
  subname varchar(50),
  primary key (id)
) engine = innodb auto_increment = 1 default character set = utf8;
insert into t1(id, name) values (1,'a'),(2,'b'),(3,'c');
insert into t2(pid, subname) values (1,'a_1'),(1,'a_2'),(1,'a_3'),
                                    (2,'b_1'),(2,'b_2'),(2,'b_3');
create table t2_1 as
    select * from t2 where id in ( select max(id) from t2 group by pid );
create view v2 as
    select * from t2 where id in ( select max(id) from t2 group by pid );

在以下查询中,左表始终为t1,右表始终等于select * from t2 where id in ( select max(id) from t2 group by pid )

使用子查询左连接:

select t1.id, t1.name, t22.id as sid, t22.subname
from t1 left join (
    select * from t2 where id in ( select max(id) from t2 group by pid )
    ) as t22
on (t1.id = t22.pid);

结果mariadb 10.1.21没问题:

+----+------+------+---------+
| id | name | sid  | subname |
+----+------+------+---------+
|  1 | a    |    3 | a_3     |
|  2 | b    |    6 | b_3     |
|  3 | c    | NULL | NULL    |
+----+------+------+---------+

导致mariadb 10.2.11或10.2.13错误:

+----+------+------+---------+
| id | name | sid  | subname |
+----+------+------+---------+
|  1 | a    |    3 | a_3     |
|  2 | b    |    6 | b_3     |
+----+------+------+---------+

左表连接

select t1.id, t1.name, t2_1.id as sid, t2_1.subname
from t1 left join t2_1
on (t1.id = t2_1.pid);

结果mariadb 10.1.21没问题:

+----+------+------+---------+
| id | name | sid  | subname |
+----+------+------+---------+
|  1 | a    |    3 | a_3     |
|  2 | b    |    6 | b_3     |
|  3 | c    | NULL | NULL    |
+----+------+------+---------+

结果mariadb 10.2.11或10.2.13没问题:

+----+------+------+---------+
| id | name | sid  | subname |
+----+------+------+---------+
|  1 | a    |    3 | a_3     |
|  2 | b    |    6 | b_3     |
|  3 | c    | NULL | NULL    |
+----+------+------+---------+

左边加入视图:

select t1.id, t1.name, t22.id as sid, t22.subname
from t1 left join v2 as t22
on (t1.id = t22.pid);

结果mariadb 10.1.21没问题:

+----+------+------+---------+
| id | name | sid  | subname |
+----+------+------+---------+
|  1 | a    |    3 | a_3     |
|  2 | b    |    6 | b_3     |
|  3 | c    | NULL | NULL    |
+----+------+------+---------+

导致mariadb 10.2.11或10.2.13错误

+----+------+------+---------+
| id | name | sid  | subname |
+----+------+------+---------+
|  1 | a    |    3 | a_3     |
|  2 | b    |    6 | b_3     |
+----+------+------+---------+

0 个答案:

没有答案