获得有关约束的完整信息

时间:2012-01-13 15:22:31

标签: mysql foreign-keys primary-key

我想创建如下结果的查询:

column_name, constraint_name, constraint_type, referenced_table_name, referenced_column_name

我尝试过这样的事情

SELECT col.column_name, cons.constraint_name, cons.constraint_type,col.referenced_table_name, col.referenced_column_name
FROM information_schema.table_constraints cons, information_schema.key_column_usage col
WHERE col.table_name = 'countries'
AND cons.constraint_name = col.constraint_name
AND cons.table_name = col.table_name

但是,我错了column_name ... :(

请帮帮我......

2 个答案:

答案 0 :(得分:0)

SELECT `COLUMN_NAME`, `CONSTRAINT_NAME`, `REFERENCED_TABLE_NAME`, `REFERENCED_COLUMN_NAME`
FROM `information_schema`.`KEY_COLUMN_USAGE`
WHERE `TABLE_NAME` = 'countries'
AND `CONSTRAINT_NAME` <> 'PRIMARY';

我不知道constraint_type。我没有在information_schema中找到这个专栏。

答案 1 :(得分:0)

主键始终具有名称'PRIMARY',外键始终具有referenced_table_name,因此您可以从一个表中获取该信息 - key_column_usage

SELECT
  column_name,
  constraint_name,
  CASE
    WHEN constraint_name = 'PRIMARY' THEN 'PRIMARY KEY'
    WHEN referenced_table_name IS NULL THEN 'UNIQUE KEY'
    ELSE 'FOREIGN KEY'
  END constraint_type,
  referenced_table_name,
  referenced_column_name
FROM
  information_schema.key_column_usage;