Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ตรวจสอบ Composite Primary Key ในตาราง MySQL ด้วย information_schema

Composite Primary Key (คีย์หลักรวม) คือ Primary Key ที่ประกอบด้วยหลายคอลัมน์ร่วมกัน ใน MySQL สามารถตรวจสอบว่าตารางใดมี Composite PK ได้โดยสืบค้นจาก information_schema.KEY_COLUMN_USAGE

ตัวอย่างการใช้งาน

สร้างตารางและเพิ่ม Composite Primary Key:

mysql> create table DemoTable1324 (
    StudentId int,
    StudentName varchar(20),
    StudentAge int,
    StudentCountryName varchar(20)
);
mysql> alter table DemoTable1324 ADD CONSTRAINT constr_IdAgeCountry PRIMARY KEY (StudentId, StudentAge, StudentCountryName);

คำสั่งตรวจสอบจำนวนคอลัมน์ใน Primary Key

mysql> select count(*) AS Total
    -> from information_schema.KEY_COLUMN_USAGE
    -> where table_name='DemoTable1324' and table_schema=database();

ผลลัพธ์

+-------+
| Total |
+-------+
| 3     |
+-------+

คำอธิบาย:

  • ผลลัพธ์ 3 หมายถึงมี 3 คอลัมน์ใน Primary Key (StudentId, StudentAge, StudentCountryName) = Composite PK
  • หากผลลัพธ์เป็น 1 = Primary Key แบบเดี่ยว (Single Column PK)
  • table_schema=database() จำกัดเฉพาะฐานข้อมูลปัจจุบัน
  • ตาราง KEY_COLUMN_USAGE เก็บข้อมูลคีย์ทุกประเภท (PK, FK, Unique)

คำสั่งเพิ่มเติม: ดูรายละเอียดคอลัมน์ที่เป็น PK

SELECT column_name, ordinal_position
FROM information_schema.KEY_COLUMN_USAGE
WHERE table_name='DemoTable1324' AND table_schema=database() AND constraint_name='PRIMARY'
ORDER BY ordinal_position;