微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

MySQL 8 中左连接的意外结果

如何解决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 举报,一经查实,本站将立刻删除。