MySQL操作数据库和表的常用命令新手教程

2019-01-05 10:05:21王冬梅


mysql> create table if not exists db_test.tb_test(
    -> id int unsigned not null auto_increment,
    -> firstname varchar(25) not null,
    -> lastname varchar(25) not null,
    -> email varchar(45) not null,
    -> phone varchar(10) not null,
    -> primary key(id));
Query OK, 0 rows affected, 1 warning (0.00 sec)

无论是否已经创建,都会在返回到命令提示窗口时显示“Query OK”消息。

3.复制表

基于现有的表创建新表是一项很容易的任务。以下代码将得到tb_test表的一个副本,名为tb_test2:


mysql> create table tb_test2 select * from db_test.tb_test;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

将向数据库增加一个相同的表tb_test2。而有的时候,可能希望只基于现有表的几个列创建一个表。通过create select语句中指定列就可以实现:


mysql> describe tb_test;
+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| id        | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| firstname | varchar(25)      | NO   |     | NULL    |                |
| lastname  | varchar(25)      | NO   |     | NULL    |                |
| email     | varchar(45)      | NO   |     | NULL    |                |
| phone     | varchar(10)      | NO   |     | NULL    |                |
+-----------+------------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)
mysql> create table tb_test2 select id, firstname, lastname, email from tb_test;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> describe tb_test2;
+-----------+------------------+------+-----+---------+-------+
| Field     | Type             | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| id        | int(10) unsigned | NO   |     | 0       |       |
| firstname | varchar(25)      | NO   |     | NULL    |       |
| lastname  | varchar(25)      | NO   |     | NULL    |       |
| email     | varchar(45)      | NO   |     | NULL    |       |
+-----------+------------------+------+-----+---------+-------+
4 rows in set (0.01 sec)