2011-03-17 29 views
0

是否有任何查询来获取具有主键外键引用的列列表?如何查询表格的列描述?

SELECT column_name, data_type, CHARacter_maximum_length 
FROM DBTIME.information_schema.columns 
WHERE table_name = 'Table Name' 

从这个查询我得到的数据类型和列的最大长度。除此之外,我需要知道它的外键主键引用。请帮助...

回答

0
SELECT 
    K_Table = FK.TABLE_NAME, 
    FK_Column = CU.COLUMN_NAME, 
    PK_Table = PK.TABLE_NAME, 
    PK_Column = PT.COLUMN_NAME, 
    Constraint_Name = C.CONSTRAINT_NAME 
FROM 
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C 
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK 
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME 
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK 
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME 
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU 
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME 
INNER JOIN (
    SELECT 
     i1.TABLE_NAME, 
     i2.COLUMN_NAME 
    FROM 
     INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 
     ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME 
    WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' 
) PT 
    ON PT.TABLE_NAME = PK.TABLE_NAME 
+0

我将最后一部分分割以获得确切结果PT.TABLE_NAME ='Company'和PK.TABLE_NAME ='Company'...谢谢...... :) – NewBie 2011-03-17 10:53:14

0
SELECT * FROM information_schema.columns WHERE table_name = 'Table Name' 
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME='Table Name'// It will list all the primary key and foreign key references. 
+0

有任何疑问单独获得列的关键字类型。我的意思是,我需要知道列是主键还是外键。如果是外键,那么哪个表的字段就是哪个表。是否有可能从一个查询中找到? – NewBie 2011-03-17 06:20:56