2013-02-13 59 views
2

我正在使用它來獲取我的PRIMARY索引列。來自SHOW命令的單列

SHOW INDEX FROM `table` WHERE Key_name='PRIMARY' 

它返回一個類型,列名,KEY_NAME等

我只想Column_name列的表。

我想:

SHOW INDEX.Column_name FROM `table` WHERE Key_name='PRIMARY' 

但沒有奏效。有任何想法嗎?

回答

2

要想從主鍵(按順序)爲mydb.mytable所有列,運行以下命令:

SELECT column_name 
FROM information_schema.statistics 
WHERE table_schema='mydb' 
AND table_name='mytable' 
AND index_name='PRIMARY' 
ORDER BY seq_in_index; 

要從PRIMARY KEY獲取所有列(按順序)爲mytable當前數據庫,運行此:

SELECT column_name 
FROM information_schema.statistics 
WHERE table_schema=DATABASE() 
AND table_name='mytable' 
AND index_name='PRIMARY' 
ORDER BY seq_in_index; 

下面是一個示例表:

mysql> show create table cacti.host_snmp_cache\G 
*************************** 1. row *************************** 
     Table: host_snmp_cache 
Create Table: CREATE TABLE `host_snmp_cache` (
    `host_id` mediumint(8) unsigned NOT NULL DEFAULT '0', 
    `snmp_query_id` mediumint(8) unsigned NOT NULL DEFAULT '0', 
    `field_name` varchar(50) NOT NULL DEFAULT '', 
    `field_value` varchar(255) DEFAULT NULL, 
    `snmp_index` varchar(255) NOT NULL DEFAULT '', 
    `oid` text NOT NULL, 
    PRIMARY KEY (`host_id`,`snmp_query_id`,`field_name`,`snmp_index`), 
    KEY `host_id` (`host_id`,`field_name`), 
    KEY `snmp_index` (`snmp_index`), 
    KEY `field_name` (`field_name`), 
    KEY `field_value` (`field_value`), 
    KEY `snmp_query_id` (`snmp_query_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1 
1 row in set (0.00 sec) 

mysql> 

諾蒂奇E中的主鍵,4列

這裏是查詢的執行:

mysql> SELECT column_name 
    -> FROM information_schema.statistics 
    -> WHERE table_schema='cacti' 
    -> AND table_name='host_snmp_cache' 
    -> AND index_name='PRIMARY' 
    -> ORDER BY seq_in_index; 
+---------------+ 
| column_name | 
+---------------+ 
| host_id  | 
| snmp_query_id | 
| field_name | 
| snmp_index | 
+---------------+ 
4 rows in set (0.00 sec) 

mysql> 

使用GROUP_CONCAT,你可以收集列名到CSV列表

mysql> SELECT GROUP_CONCAT(column_name) PrimaryKeyColumns 
    -> FROM information_schema.statistics 
    -> WHERE table_schema='cacti' 
    -> AND table_name='host_snmp_cache' 
    -> AND index_name='PRIMARY' 
    -> ORDER BY seq_in_index; 
+---------------------------------------------+ 
| PrimaryKeyColumns       | 
+---------------------------------------------+ 
| host_id,snmp_query_id,field_name,snmp_index | 
+---------------------------------------------+ 
1 row in set (0.01 sec) 

mysql> 

試試看! !

+0

完美答案。在搜索時,我看到其他3-4個類似的答案,每個答案都不起作用,或者我的帳戶沒有足夠高的權限。這完美的作品:) – hellohellosharp 2013-02-13 19:24:22