MySQL:如何查看表上的所有约束?
我正在学习SQL,令我困扰的是,我似乎无法在表上找到所有约束。 我用创建表
create table t2
(a integer not null primary key,
b integer not null, constraint c1 check(b>0),
constraint fk1 foreign key(a) references t1(a));
并添加了一个约束
alter table t2
add constraint c2 check (b<20);
然后,我尝试查看所有(四个)约束
show table status
from tenn #-->the name of my database
like 't2';
然后
show create table t2;
and then
select *
from information_schema.key_column_usage
where table_name='t2';
最后
select *
from information_schema.table_constraints
where table_name='t2';
但是这些都不显示所有四个约束。 谁能告诉我如何看到所有这些?
非常感谢!
Alexander asked 2020-08-04T19:55:26Z
8个解决方案
59 votes
select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME, REFERENCED_TABLE_NAME
from information_schema.KEY_COLUMN_USAGE
where TABLE_NAME = 'table to be checked';
RRM answered 2020-08-04T19:55:39Z
22 votes
查看当前表及其约束的最简单方法是使用:
SHOW CREATE TABLE mytable;
这将向您确切显示将输入什么SQL以定义其当前形式的表结构。
John Foley answered 2020-08-04T19:56:04Z
20 votes
MySQL不支持检查约束。 对该SQL进行解析,接受,然后以静默方式忽略,而不会向用户发送任何消息。
由于未创建检查约束,因此您将看不到它。
a_horse_with_no_name answered 2020-08-04T19:56:28Z
12 votes
您可以使用此:
select
table_name,column_name,referenced_table_name,referenced_column_name
from
information_schema.key_column_usage
where
referenced_table_name is not null
and table_schema = 'my_database'
and table_name = 'my_table'
为了获得更好的格式输出,请使用以下命令:
select
concat(table_name, '.', column_name) as 'foreign key',
concat(referenced_table_name, '.', referenced_column_name) as 'references'
from
information_schema.key_column_usage
where
referenced_table_name is not null
and table_schema = 'my_database'
and table_name = 'my_table'
Abhishek Gupta answered 2020-08-04T19:56:52Z
6 votes
您可以从information_schema.table_constraints像这样获得它:
SELECT *
FROM information_schema.table_constraints
WHERE table_schema = schema()
AND table_name = 'table_name';
blackbishop answered 2020-08-04T19:57:12Z
3 votes
外键约束在以下命令的输出的“注释”列中列出:
SHOW TABLE STATUS FROM db_name LIKE 'tbl_name';
sreimer answered 2020-08-04T19:57:32Z
2 votes
不幸的是,MySQL不支持SQL检查约束。 当您在查询中定义它们时,它们将被忽略。
Karan Motwani answered 2020-08-04T19:57:52Z
0 votes
用SQL导出数据库表。
如果您具有phpmyadmin,则可以通过访问“导出”标签来实现。 如果选择“自定义”导出方法,请确保在“特定于格式的选项”部分下选择“结构”或“结构和数据”。
示例.sql导出代码段:
--
-- Table structure for table `customers`
--
CREATE TABLE `customers` (
`username` varchar(50) NOT NULL,
`fullname` varchar(100) NOT NULL,
`postalcode` varchar(50) NOT NULL,
PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
...
hawk8 answered 2020-08-04T19:58:21Z