IT박스

테이블의 기본 키를 얻는 방법은 무엇입니까?

itboxs 2020. 11. 13. 07:57
반응형

테이블의 기본 키를 얻는 방법은 무엇입니까?


mysql-database에서 기본 키 필드의 이름을 얻는 방법이 있습니까? 예를 들면 :

다음과 같은 테이블이 있습니다.

+----+------+
| id | name |
+----+------+
| 1  | Foo1 |
| 2  | Foo2 |
| 3  | Foo3 |
+----+------+

필드 ID가 기본 키인 경우 (자동 증가가 있지만 사용할 수 없습니다). PHP에서 필드 이름 "id"를 어떻게 검색 할 수 있습니까?


더 좋은 방법은 SHOW KEYSinformation_schema에 항상 액세스 할 수있는 것은 아니기 때문에 사용하는 것입니다 . 다음 작업 :

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'

Column_name에는 기본 키의 이름이 포함됩니다.


다음은 기본 키 열 이름입니다.

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 key_column_usage.column_name
FROM   information_schema.key_column_usage
WHERE  table_schema = schema()             -- only look in the current db
AND    constraint_name = 'PRIMARY'         -- always 'PRIMARY' for PRIMARY KEY constraints
AND    table_name = '<your-table-name>'    -- specify your table.

이건 어때.

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';

사용하다:

show columns from tablename where `Key` = "PRI";

각 테이블을 실행할 필요없이 한 번에 PHP를 통해 기본 키 목록을 동적으로 생성하려는 경우 사용할 수 있습니다.

SELECT TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.key_column_usage WHERE table_schema = '$database_name' AND CONSTRAINT_NAME = 'PRIMARY' 

이렇게하려면 information.schema에 대한 액세스 권한이 있어야합니다.


PHP 접근 방식의 경우 mysql_field_flags 를 사용할 수 있습니다.

$q = mysql_query('select * from table limit 1');

for($i = 0; $i < mysql_num_fields(); $i++)
    if(strpos(mysql_field_tags($q, $i), 'primary_key') !== false)
        echo mysql_field_name($q, $i)." is a primary key\n";

가능한 가장 짧은 코드는 다음과 같은 것 같습니다.

// $dblink contain database login details 
// $tblName the current table name 
$r = mysqli_fetch_assoc(mysqli_query($dblink, "SHOW KEYS FROM $tblName WHERE Key_name = 'PRIMARY'")); 
$iColName = $r['Column_name']; 

I've got it, finally!

<?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);
}
}

?>

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 herehere


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 -

*************************** 1. row ***************************
        Table: products
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: product_id
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment: 

To just display primary key from the table use :-

SHOW INDEXES FROM table_name WHERE Key_name = 'PRIMARY'

If you have spatial tables in your database, use:

SHOW KEYS FROM table WHERE Key_name = 'PRIMARY' OR Key_name = 'OGR_FID'

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";

SELECT k.column_name
FROM information_schema.key_column_usage k   
WHERE k.table_name = 'YOUR TABLE NAME' AND k.constraint_name LIKE 'pk%'

I would recommend you to watch all the fields

참고URL : https://stackoverflow.com/questions/2341278/how-to-get-primary-key-of-table

반응형