
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Two Columns as Primary Key with Auto Increment in MySQL
Achieve this using MyISAM Engine. Here is an example of two columns as primary key with auto-increment.
Creating a table with two columns as primary key −
mysql> create table TwoPrimaryKeyTableDemo -> ( -> Result ENUM('First','Second','Third','Fail') not null, -> StudentId int not null auto_increment, -> StudentName varchar(200) not null, -> Primary key(Result,StudentId) -> ) -> ENGINE=MyISAM; Query OK, 0 rows affected (0.20 sec)
Inserting records into table
mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('John','Fail'); Query OK, 1 row affected (0.42 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result)values('Carol','First'); Query OK, 1 row affected (0.09 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Smith','Third'); Query OK, 1 row affected (0.05 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Johnson','Second'); Query OK, 1 row affected (0.03 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Johnson','Third'); Query OK, 1 row affected (0.06 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Carol','Second'); Query OK, 1 row affected (0.18 sec) mysql> insert into TwoPrimaryKeyTableDemo(StudentName,Result) values('Carol','Fail'); Query OK, 1 row affected (0.05 sec)
Now we can check the records with the help of select statement with order by clause. The query is as follows.
mysql> select *from TwoPrimaryKeyTableDemo order by StudentId,Result;
The following is the output −
+--------+-----------+-------------+ | Result | StudentId | StudentName | +--------+-----------+-------------+ | First | 1 | Carol | | Second | 1 | Johnson | | Third | 1 | Smith | | Fail | 1 | John | | Second | 2 | Carol | | Third | 2 | Johnson | | Fail | 2 | Carol | +--------+-----------+-------------+ 7 rows in set (0.00 sec)
Advertisements