Using AUTO_INCREMENT : Foreign Keys « Table « MySQL Tutorial






The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows:

mysql>
mysql> CREATE TABLE employee (
    ->      id MEDIUMINT NOT NULL AUTO_INCREMENT,
    ->      name CHAR(30) NOT NULL,
    ->      PRIMARY KEY (id)
    ->  );
Query OK, 0 rows affected (0.01 sec)

mysql>
mysql> desc employee;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | mediumint(9) | NO   | PRI | NULL    | auto_increment |
| name  | char(30)     | NO   |     |         |                |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.02 sec)

mysql>
mysql> INSERT INTO employee (name) VALUES ('A'),
    ->                                    ('B'),
    ->                                    ('C'),
    ->                                    ('D'),
    ->                                    ('E'),
    ->                                    ('F');
Query OK, 6 rows affected (0.00 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql>
mysql> SELECT * FROM employee;
+----+------+
| id | name |
+----+------+
|  1 | A    |
|  2 | B    |
|  3 | C    |
|  4 | D    |
|  5 | E    |
|  6 | F    |
+----+------+
6 rows in set (0.00 sec)

mysql>
mysql> drop table employee;
Query OK, 0 rows affected (0.00 sec)

mysql>








4.16.Foreign Keys
4.16.1.Using Foreign Keys
4.16.2.Using AUTO_INCREMENT
4.16.3.Implement a many-to-many map
4.16.4.One table with two foreign keys
4.16.5.Alter table to drop primary key and foreign key
4.16.6.Add Index and primary key to a table in table creation command
4.16.7.FOREIGN KEY ON DELETE CASCADE ON UPDATE CASCADE