MySQL 8 中左连接的意外结果

问题描述

我使用的是 mysql-8.0.23。

我正在尝试获取模式“test”中没有主键的表列表。 我设法使用“不在”语句(参见下面的代码)获得了预期的结果。 但我想对左连接做同样的事情。

这是我的疑问:

--------------
-- LIST ALL TABLES IN SCHEMA 'test'
--------------
select
    t.table_name
from
    information_schema.tables t
where
    t.table_schema = 'test'
and t.table_type = 'BASE TABLE'

+------------------+
| TABLE_NAME       |
+------------------+
| table_with_pk    |
| table_without_pk |
+------------------+



--------------
-- LIST TABLES WITH PRIMARY KEY
--------------
select
    tc.table_name
from
    information_schema.table_constraints tc
where
    tc.table_schema = 'test'
and tc.constraint_type = 'PRIMARY KEY'

+---------------+
| TABLE_NAME    |
+---------------+
| table_with_pk |
+---------------+



--------------
-- LIST TABLES WITHOUT PRIMARY KEY : using "not in" ==> OK
--------------
select
    t.table_name
from
    information_schema.tables t
where
    t.table_schema = 'test'
and t.table_type = 'BASE TABLE'
and t.table_name not in
    (
        select
            tc.table_name
        from
            information_schema.table_constraints tc
        where
            tc.table_schema = 'test'
        and tc.constraint_type = 'PRIMARY KEY'
    )

+------------------+
| TABLE_NAME       |
+------------------+
| table_without_pk |
+------------------+


--------------
-- LIST TABLES WITHOUT PRIMARY KEY : using "left join"   ==> NOK
--------------
select
    t.table_name,tc.constraint_type
from
    information_schema.tables t
left join information_schema.table_constraints tc
    on t.table_name = tc.table_name
    and tc.table_schema = t.table_schema
    and tc.constraint_type = 'PRIMARY KEY'
where
    t.table_schema = 'test'
and t.table_type = 'BASE TABLE'

+------------------+-----------------+
| TABLE_NAME       | CONSTRAINT_TYPE |
+------------------+-----------------+
| table_with_pk    | PRIMARY KEY     |
| table_without_pk | PRIMARY KEY     |
+------------------+-----------------+

我期待上次请求的结果如下:

+------------------+-----------------+
| TABLE_NAME       | CONSTRAINT_TYPE |
+------------------+-----------------+
| table_with_pk    | PRIMARY KEY     |
| table_without_pk | NULL            |
+------------------+-----------------+

你能帮我理解我做错了什么吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)