Composite Key और Unique Key
Composite key क्या है
Composite key दो या ज़्यादा columns साथ से बनी primary key है। यह तब इस्तेमाल होती है जब कोई एक column row को विशिष्ट न पहचाने, पर संयोजन करे। जैसे, एक student कई courses में enrol कर सकता है, तो न student_id न course_id अकेले unique है — पर साथ में हैं।
आपको इसकी ज़रूरत क्यों
एक enrolments table सोचिए जो students को courses से जोड़ती है। वही student कई rows में दिखता है (कई courses), और वही course कई rows में दिखता है (कई students)। कोई एक column unique नहीं। पर जोड़ी (student_id, course_id) unique होनी चाहिए — student को वही course दो बार enrol नहीं करना चाहिए।
Composite key बनाना
CREATE TABLE enrollments (
student_id INT,
course_id INT,
grade CHAR(1),
PRIMARY KEY (student_id, course_id)
);
दोनों columns एक PRIMARY KEY (...) clause में list करना उन्हें composite key बनाता है। संयोजन unique होना चाहिए, हालाँकि हर column अकेले दोहरा सकता है।
यह uniqueness कैसे लागू करती है
INSERT INTO enrollments VALUES (1, 101, 'A'); -- ok INSERT INTO enrollments VALUES (1, 102, 'B'); -- ok (वही student, नया course) INSERT INTO enrollments VALUES (1, 101, 'C'); -- ERROR: duplicate जोड़ी
Student 1 courses 101 और 102 ले सकता है, पर course 101 दो बार enrol नहीं कर सकता — composite key duplicate संयोजन रोकती है।
Foreign keys के साथ
CREATE TABLE enrollments (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students(id),
FOREIGN KEY (course_id) REFERENCES courses(id)
);
Link table में, composite key का हर हिस्सा अक्सर foreign key भी होता है। यहाँ दो columns students और courses tables दर्शाते हैं, उन्हें जोड़ते हुए हर जोड़ी unique रखकर।
Composite बनाम single key
| बात | Single key | Composite key |
|---|---|---|
| Columns | एक | दो या ज़्यादा |
| Unique on | वो column | संयोजन |
| आम इस्तेमाल | सामान्य tables | Link tables (M:N) |
| Individual दोहराव | Allowed नहीं | Allowed अगर जोड़ी अलग |
आम गलतियाँ
- एकल columns के unique होने की उम्मीद। सिर्फ़ संयोजन unique है।
- दो PRIMARY KEY clauses इस्तेमाल करना। इसके बजाय सारे columns एक clause में list कीजिए।
- क्रम की confusion। Columns एक key बनाते हैं; उनका क्रम indexing प्रभावित कर सकता है।
- जहाँ single id काम करे वहाँ composite key इस्तेमाल करना। सिर्फ़ ज़रूरत पड़ने पर इस्तेमाल कीजिए।
सारांश
- Composite key दो या ज़्यादा columns की primary key है।
- इसे तब इस्तेमाल कीजिए जब सिर्फ़ columns का संयोजन unique हो।
- इसे एक
PRIMARY KEY (col1, col2)clause से बनाइए। - एकल columns दोहरा सकते हैं अगर पूरा संयोजन न दोहराए।
- यह link tables में आम है, जहाँ columns foreign keys भी होते हैं।
आगे, सारे key प्रकार सीखिए keys in DBMS explained में, या auto ids AUTO_INCREMENT में।
अक्सर पूछे जाने वाले प्रश्न (FAQ)
MySQL में composite key क्या है?
Composite key कब इस्तेमाल करूँ?
MySQL में composite key कैसे बनाऊँ?
PRIMARY KEY (student_id, course_id)। MySQL फिर संयोजन को unique identifier मानता है, एक column में वही value allow करके जब तक जोड़ी unique हो।