如何在 MySQL 中获取表的主键?


要获取表的某个主键,你可以使用 show 命令。语法如下: -

SHOW INDEX FROM yourDatebaseName.yourTableName WHERE Key_name = 'PRIMARY';

比方说,我们有一个表有两个主键,一个叫“Id”,另一个叫“RollNum”。查询表如下: -

mysql> create table TwoOrMorePrimary
   −> (
   −> Id int,
   −> Name varchar(200), 
   −> RollNum int
   −> ,
   −> Primary key(Id,Age)
   −> );
Query OK, 0 rows affected (0.85 sec)

应用上述语法来获取表的某个主键。查询如下: -

mysql> SHOW INDEX FROM business.TwoOrMorePrimary
−> WHERE Key_name = 'PRIMARY';

以下是输出: -

+------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table            | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| twoormoreprimary |          0 | PRIMARY  | 1            | Id          | A         | 0           | NULL     | NULL   |      | BTREE      |         |               | YES     | NULL       |
| twoormoreprimary |          0 | PRIMARY  | 2            | RollNum     | A         | 0           | NULL     | NULL   |      | BTREE      |         |               | YES      | NULL      |
+------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
2 rows in set (0.12 sec)

更新于: 30-Jul-2019

4K+ 次浏览

开启你的 职业生涯

完成课程以获得认证

开始学习
广告