我有以下SQL代码,它返回数据库中的表,以及每个表中的主键字段。
SELECT Keys.TABLE_NAME As 'Table Name',
Keys.COLUMN_NAME AS 'Primary Key'
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS Constraints
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS Keys
ON Constraints.TABLE_NAME = Keys.TABLE_NAME
AND Constraints.CONSTRAINT_NAME = Keys.CONSTRAINT_NAME
WHERE Constraints.CONSTRAINT_TYPE = 'PRIMARY KEY'
实际上,它只显示那些具有主键的表。如何修改sql以显示所有表,而那些没有主键的表将在“Primary Key”列中显示“null”?
答案 0 :(得分:1)
为此,您需要从所有表的列表开始,然后使用左外连接来连接表:
SELECT t.TABLE_NAME As 'Table Name',
Keys.COLUMN_NAME AS 'Primary Key'
FROM INFORMATION_SCHEMA.TABLES t left outer join
INFORMATION_SCHEMA.TABLE_CONSTRAINTS Constraints
on t.TABLE_NAME = Constraints.Table_name and
t.Table_Schema = Constraints.Table_Schema left outer join
INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS Keys
ON Constraints.TABLE_NAME = Keys.TABLE_NAME and
Constraints.CONSTRAINT_NAME = Keys.CONSTRAINT_NAME and
Constraints.CONSTRAINT_TYPE = 'PRIMARY KEY'
答案 1 :(得分:1)
默认情况下,“join”是内部联接,如果根据联接条件在另一个表中存在相应的行,则只会显示一行。因此,您不希望在此处使用直接连接,您需要左连接,右连接或完全连接,这允许表返回没有匹配的行。
但是在这里你不能只是切换到左连接,因为table_constraints只列出有约束的那些,并且你的whereint约束将过滤掉没有主键的行。
因此,您可以引入information_schema.tables以包含每个表,然后将主键条件移动到连接条件而不是where子句。它可能看起来像:
SELECT t.TABLE_NAME As 'Table Name',
Keys.COLUMN_NAME AS 'Primary Key'
FROM
INFORMATION_SCHEMA.TABLES as t
left join
INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS Constraints
on t.TABLE_NAME = constraints.TABLE_NAME and t.TABLE_SCHEMA = constraints.TABLE_SCHEMA
left JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS Keys
ON Constraints.TABLE_NAME = Keys.TABLE_NAME
AND Constraints.CONSTRAINT_NAME = Keys.CONSTRAINT_NAME
and Constraints.CONSTRAINT_TYPE = 'PRIMARY KEY'