3

如何识别任何 Mysql 数据库表中的复合主键?或者

编辑 2 应该使用什么 sql 查询来显示包含复合主键的任何表的 indees?

我在 mysql 数据库中有很多表具有 2 或 3 个主键的复合键,我正在使用 phpmyadmin,我必须编写一个 php 脚本来识别哪个表具有复合键,现在我可以识别主键使用查询的表

SHOW INDEXES FROM `".$row3['TABLE_NAME']."` WHERE Key_name = 'PRIMARY'

这给了我我想要的东西,但现在我怎样才能找到我有复合键的索引?

编辑 1

在丹尼尔图像评论的上下文中,用于查看 phpmyadmin 中的复合主键

复合主键在 phpmyadmin 中如下所示: 替代文字

4

2 回答 2

4

更新:

除了更新的问题,您可能希望在 PHP 脚本中使用以下内容:

SELECT COUNT(*) num_keys 
FROM   information_schema.KEY_COLUMN_USAGE     
WHERE  table_name ='tb' AND constraint_name = 'PRIMARY';

num_keys如果表tb具有复合主键,则此查询将返回> 1。


我不确定我是否理解您想要实现的目标,但您可能需要考虑SHOW INDEX如下使用:

CREATE TABLE tb (a int, b int, c int);
Query OK, 0 rows affected (0.21 sec)

ALTER TABLE tb ADD CONSTRAINT pk_tb PRIMARY KEY (a, b);
Query OK, 0 rows affected (0.06 sec)

SHOW INDEX FROM tb WHERE key_name='PRIMARY';
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| tb    |          0 | PRIMARY  |            1 | a           | A         |        NULL |     NULL | NULL   |      | BTREE      |         |
| tb    |          0 | PRIMARY  |            2 | b           | A         |           0 |     NULL | NULL   |      | BTREE      |         |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
2 rows in set (0.02 sec)

SHOW INDEX如果它不是一个复合键,你只会在查询中得到一行:

CREATE TABLE tb2 (a int, b int, c int);
Query OK, 0 rows affected (0.05 sec)

ALTER TABLE tb2 ADD CONSTRAINT pk_tb PRIMARY KEY (a);
Query OK, 0 rows affected (0.05 sec)

SHOW INDEX FROM tb2 WHERE key_name='PRIMARY';
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| tb2   |          0 | PRIMARY  |            1 | a           | A         |           0 |     NULL | NULL   |      | BTREE      |         |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
1 row in set (0.02 sec)
于 2010-05-17T11:27:23.667 回答
1
SELECT COUNT( *  ) num_keys
FROM information_schema.KEY_COLUMN_USAGE
WHERE table_name = 'jos_modules_menu'
AND constraint_name = 'PRIMARY'
AND table_schema = 'pranav_test'

谢谢丹尼尔和普拉纳夫 :)

于 2010-05-17T12:37:25.330 回答