Computer >> Máy Tính >  >> Lập trình >> MySQL

Làm cách nào để biết liệu một cột có phải là khóa chính trong MySQL hay không?

Để biết liệu một cột có phải là khóa chính hay không, hãy sử dụng COLUMN_NAME và COLUMN_KEY ='PRI'. Với đó, toàn bộ cú pháp như sau -

select column_name, case when column_key= 'PRI' then 'yourMessage1' else ''yourMessage2' end as anyAliasName
from information_schema.columns
where table_schema =database()
and `table_name` = yourTableName
order by `table_name`, ordinal_position;

Để hiểu cú pháp trên, chúng ta hãy tạo một bảng -

mysql> create table DemoTable1886
   (
   Id int NOT NULL,
   FirstName varchar(20),
   LastName varchar(20),
   Age int,
   DateOfBirth datetime,
   Education varchar(40),
   PRIMARY KEY(Id)
   );
Query OK, 0 rows affected (0.00 sec)

Đây là truy vấn để biết liệu một cột cụ thể có phải là khóa chính hay không -

mysql> select column_name, case when column_key= 'PRI' then 'This is a Primary key Column' else 'This is not a Primary key Column' end as Output
   from information_schema.columns
   where table_schema =database()
   and `table_name` = 'DemoTable1886'
   order by `table_name`, ordinal_position;

Điều này sẽ tạo ra kết quả sau -

+-------------+--------------------------------+
| COLUMN_NAME | Output                         |
+-------------+--------------------------------+
| Id          | This is a Primary key Column   |
| FirstName   |This is not a Primary key Column|
| LastName    |This is not a Primary key Column|
| Age         |This is not a Primary key Column|
| DateOfBirth |This is not a Primary key Column|
| Education   |This is not a Primary key Column|
+-------------+--------------------------------+
6 rows in set (0.00 sec)