SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING(constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
AND t.table_schema='YourDatabase'
AND t.table_name='YourTable';
SELECT kcu.column_name, kcu.ordinal_position
FROM information_schema.table_constraints tc
INNER JOIN information_schema.key_column_usage kcu
ON tc.CONSTRAINT_CATALOG = kcu.CONSTRAINT_CATALOG
AND tc.CONSTRAINT_SCHEMA = kcu.CONSTRAINT_SCHEMA
AND tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
WHERE tc.table_schema = schema() -- only look in the current schema
AND tc.constraint_type = 'PRIMARY KEY'
AND tc.table_name = '<your-table-name>' -- specify your table.
ORDER BY kcu.ordinal_position
<?php
function mysql_get_prim_key($table){
$sql = "SHOW INDEX FROM $table WHERE Key_name = 'PRIMARY'";
$gp = mysql_query($sql);
$cgp = mysql_num_rows($gp);
if ($cgp > 0) {
// Note I'm not using a while loop because I never use more than one prim key column
$agp = mysql_fetch_array($gp);
extract($agp);
return($Column_name);
} else {
return(false);
}
}
?>
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
AND TABLE_NAME = 'Your Table name'
AND COLUMN_KEY = 'PRI';
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Your Database'
AND TABLE_NAME = 'Your Table name'
AND COLUMN_KEY = 'UNI';
I use SHOW INDEX FROM table ; it gives me alot of informations ; if the key is unique, its sequenece in the index, the collation, sub part, if null, its type and comment if exists, see screenshot here
MySQL has a SQL query "SHOW INDEX FROM" which returns the indexes from a table.
For eg. - the following query will show all the indexes for the products table:-
SHOW INDEXES FROM products \G
It returns a table with type, column_name, Key_name, etc. and displays output with all indexes and primary keys as -
You should use PRIMARY from key_column_usage.constraint_name = "PRIMARY"
sample query,
SELECT k.column_name as PK, concat(tbl.TABLE_SCHEMA, '.`', tbl.TABLE_NAME, '`') as TABLE_NAME
FROM information_schema.TABLES tbl
JOIN information_schema.key_column_usage k on k.table_name = tbl.table_name
WHERE k.constraint_name='PRIMARY'
AND tbl.table_schema='MYDB'
AND tbl.table_type="BASE TABLE";