当前位置: 首页 > 科技观察

DBA技术分享--MySQL关于主键的三种查询PrimaryKeys

时间:2023-03-21 00:00:10 科技观察

概述分享作为一名DBA在日常工作中,关于mysql主键的三种常用查询语句如下:列出所有主键(PK)及其名称MySQL数据库列表。列出用户数据库(模式)中没有主键的表。该查询显示用户数据库(模式)中存在多少没有主键的表,以及这些表占总表的百分比。列出MySQL数据库中的所有主键(PK)及其列selecttab.table_schemaasdatabase_schema,sta.index_nameaspk_name,sta.seq_in_indexascolumn_id,sta.column_name,tab.table_namefrominformation_schema.tablesastabinnerjoininformation_schema.statistics作为sta.table_schema=tab.table_schemaandsta.table_name=tab.table_nameandsta.index_name='primary'wheretab.table_schema='yourdatabasename'andtab.table_type='BASETABLE'orderbytab.table_name,column_id;列描述:table_schema-PK数据库(模式)名称。pk_name-PK约束名称。column_id-索引中列的ID(1,2,...)。2或更高表示该键是复合键(包含多于一列)。column_name-主键列名。table_name-PK表名。示例输出:输出结果说明:一行:代表一个主键列。RowRange:数据库中所有PK约束的列(模式)。排序依据:表名、列ID。列出用户数据库(模式)中没有主键的表selecttab.table_schemaasdatabase_name,tab.table_namefrominformation_schema.tablestableftjoininformation_schema.table_constraintstcoontab.table_schema=tco.table_schemaandtab.table_name=tco.table_nameandtco.constraint_type='PRIMARYKEY'wheretco.constraint_typeisnullandtab.table_schemanotin('mysql','information_schema','performance_schema','sys')和tab.table_type='BASETABLE'--andtab.table_schema='sakila'--按tab.table_schema,tab.table_name将模式名称放在此处;注意:如果您需要特定数据库(架构)的信息,请取消注释table_schema行并提供您的数据库名称。列说明:database_name-数据库(模式)名称。table_name-表名。示例:输出结果说明:一行:表示数据库中没有主键的表(schema)。行范围:数据库中没有主键的所有表(模式)。排序依据:数据库(模式)名称、表名称。查询显示用户数据库(schema)中有多少表没有主键,占总表的百分比selectcount(*)asall_tables,count(*)-count(tco.constraint_type)asno_pk_tables,cast(100.0*(count(*)-count(tco.constraint_type))/count(*)asdecimal(5,2))asno_pk_percentfrominformation_schema.tablestableftjoininformation_schema.table_constraintstcoontab.table_schema=tco.table_schemaandtab.table_name=总拥有成本。table_nameandtco.constraint_type='PRIMARYKEY'wheretab.table_type='BASETABLE'--andtab.table_schema='database_name'--把你的数据库名放在这里,tab.table_schemanotin('mysql','information_schema','sys','performance_schema');列说明:all_tables-数据库中所有表的数量no_pk_tables-没有主键的表的数量no_pk_percent-没有主键的所有表的百分比示例: