更新:
除了更新的问题,您可能希望在 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)