用于检索列信息的SQL,包括引用

时间:2014-04-19 16:22:10

标签: mysql information-schema

我尝试查询数据库架构以检索有关列配置的信息。包含在结果集中我想要一个引用列的外键列表。希望有人在这里可能会在我的查询中发现一个错误,它总是返回一个空集。

SELECT

C.ORDINAL_POSITION          AS `position`,
C.COLUMN_DEFAULT            AS `default`,
C.IS_NULLABLE               AS `nullable`,
C.CHARACTER_MAXIMUM_LENGTH  AS `max`,
C.NUMERIC_PRECISION         AS `size`,
C.NUMERIC_SCALE             AS `scale`,
C.COLUMN_TYPE               AS `type`,
U.TABLE_NAME                AS `referenced`,

CASE C.COLUMN_NAME WHEN NULL
  THEN U.REFERENCED_COLUMN_NAME
  ELSE C.COLUMN_NAME
END AS `name`

 FROM INFORMATION_SCHEMA.COLUMNS AS C
 RIGHT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS U
   ON U.REFERENCED_TABLE_SCHEMA = C.TABLE_SCHEMA
   AND U.REFERENCED_TABLE_NAME = C.TABLE_NAME
 WHERE C.TABLE_NAME = 'my_table'
   AND C.TABLE_SCHEMA = 'my_database'
 ORDER BY `position` ASC

1 个答案:

答案 0 :(得分:0)

您需要LEFT JOIN

SELECT

    C.ORDINAL_POSITION          AS `position`,
    C.COLUMN_NAME               AS `name`
    C.COLUMN_DEFAULT            AS `default`,
    C.IS_NULLABLE               AS `nullable`,
    C.CHARACTER_MAXIMUM_LENGTH  AS `max`,
    C.NUMERIC_PRECISION         AS `size`,
    C.NUMERIC_SCALE             AS `scale`,
    C.COLUMN_TYPE               AS `type`,
    U.TABLE_NAME                AS `referencing_table`,
    U.COLUMN_NAME               AS `referencing_column`

 FROM INFORMATION_SCHEMA.COLUMNS AS C
 LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS U
   ON U.REFERENCED_TABLE_SCHEMA = C.TABLE_SCHEMA
  AND U.REFERENCED_TABLE_NAME = C.TABLE_NAME
 WHERE C.TABLE_NAME = 'my_table'
   AND C.TABLE_SCHEMA = 'my_database'
 ORDER BY `position` ASC

LEFT JOIN返回INNER JOIN将返回的所有行。此外,它返回左表(COLUMNS)中没有匹配项的任何行,右表中列的值为NULL