如何检查mysql中是否存在主键

nkoocmlb  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(321)

我尝试了几个sql脚本,但都失败了。这是我接近的地方:

SELECT *
FROM INFORMATION_SCHEMA.STATISTICS
WHERE table_schema = schema()
AND   table_name   = 'my_table_name'
AND   index_name   = 'column_name';
bis0qfac

bis0qfac1#

我想你需要下面的陈述
https://www.db-fiddle.com/f/jbdzxwpwkyichsbl1ib2rj/2

select constraint_name
  from information_schema.table_constraints
 where table_name = 'mytable'
   and table_schema = 'myschema'
   and constraint_name = 'PRIMARY';

或以下https://www.db-fiddle.com/f/jbdzxwpwkyichsbl1ib2rj/3

SELECT EXISTS(
  SELECT 1
  FROM information_schema.columns
  WHERE 
     table_name='messages'
     and column_key = 'PRI'
) As HasPrimaryKey;
zazmityj

zazmityj2#

SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = schema()
AND column_key = 'PRI'
AND table_name = 'my_table_name'
AND column_name = 'column_name';

相关问题