获取MySQL唯一键组合

时间:2011-07-28 22:59:07

标签: mysql database unique-key

如果我的表格与以下内容类似:

CREATE TABLE MyTable(
    id1Part1 INT NOT NULL,
    id1Part2 INT NOT NULL,

    id2Part1 INT NOT NULL,
    id2Part2 INT NOT NULL,

    UNIQUE KEY (id1Part1, id1Part2),
    UNIQUE KEY (id2Part1, id2Part2)
);

我现在如何询问数据库给我两个“唯一键”元组?
SHOW INDEX似乎没有这样做。)

2 个答案:

答案 0 :(得分:1)

我不确定你是否在找这样的东西

select
constraint_name,
group_concat(column_name order by ordinal_position) as cols
from information_schema.key_column_usage
where table_schema = 'db_name' and table_name = 'table_name'
group by constraint_name

答案 1 :(得分:1)

mysql不能给你两个主键。看看这个:

mysql> CREATE TABLE MyTable(
    ->     id1Part1 INT NOT NULL,
    ->     id1Part2 INT NOT NULL,
    -> 
    ->     id2Part1 INT NOT NULL,
    ->     id2Part2 INT NOT NULL,
    -> 
    ->     UNIQUE KEY (id1Part1, id1Part2),
    ->     UNIQUE KEY (id2Part1, id2Part2)
    -> );
Query OK, 0 rows affected (0.17 sec)

mysql> desc mytable;
+----------+---------+------+-----+---------+-------+
| Field    | Type    | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+-------+
| id1Part1 | int(11) | NO   | PRI | NULL    |       |
| id1Part2 | int(11) | NO   | PRI | NULL    |       |
| id2Part1 | int(11) | NO   | MUL | NULL    |       |
| id2Part2 | int(11) | NO   |     | NULL    |       |
+----------+---------+------+-----+---------+-------+

它显示只有一个主键。