创建表单常用语句

SQL语句

  • 1.创建表单
  • 2.设置主键/主码
  • 3.定义主键约束
  • 4.设置外键/外码
  • 5.定义外键
  • 4.设置值不为空
  • 5.定义约束
  • 6.插入数据
  • 7.查看表单结构
  • 8.查看表单数据

1.创建表单

格式:create table + 表单名称

mysql> create table sc;
Query OK, 0 rows affected

2.设置主键/主码

关键词:primary key

mysql> create table teacher
    -> (tno char(3) primary key);
Query OK, 0 rows affected

3.定义主键约束

格式:constraint + 约束名 + primary key(字段名1,字段名2,…,字段名n)

mysql> create table teaching
    -> (cno char(5) NOT NULL,
    -> tno char(3) NOT NULL,
    -> constraint A1 primary key(cno,tno));    

4.设置外键/外码

关键词:foreign key

mysql> create table teaching
    -> (cno char(5) foreign key);
Query OK, 0 rows affected

5.定义外键

格式:constraint + 约束名 + foreign key(外键) references 被参照表单(主键)

mysql> create table teaching
    -> (cno char(5) NOT NULL,
    -> tno char(3) NOT NULL,
    -> constraint A1 foreign key(cno,tno) references teaching(cno,tno));
Query OK, 0 rows affected

4.设置值不为空

关键词:NOT NULL

mysql> create table teaching
    -> (cno char(5) NOT NULL);
Query OK, 0 rows affected

5.定义约束

关键词:constraint + 约束名称

mysql> create table teaching
    -> (cno char(5) NOT NULL,
    -> tno char(3) NOT NULL,
    -> constraint A3 primary key(cno,tno),
    -> constraint A4 foreign key(cno,tno) references teaching(cno,tno));
Query OK, 0 rows affected

6.插入数据

格式:insert into + 表单名称(字段) + values(‘内容1’,‘内容2’)

mysql> insert into student(sno,sname,ssex,sbirthday,saddress,sdept,speciality) values('20050301','王敏','女','1989-12-23','江苏苏州','数学系','数学')
    -> ;
Query OK, 1 row affected

7.查看表单结构

mysql> desc student;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| sno        | char(10)    | NO   | PRI | NULL    |       |
| sname      | varchar(8)  | YES  |     |         |       |
| ssex       | char(2)     | YES  |     |         |       |
| sbirthday  | datetime    | YES  |     | NULL    |       |
| saddress   | varchar(50) | YES  |     |         |       |
+------------+-------------+------+-----+---------+-------+
7 rows in set

8.查看表单数据

mysql> select * from student;
+----------+-------+------+---------------------+----------+
| sno      | sname | ssex | sbirthday           | saddress |
+----------+-------+------+---------------------+----------+
| 20050101 | 李勇  || 1987-01-12 00:00:00 |    山东济南 | 
| 20050201 | 刘晨  || 1988-06-04 00:00:00 |    山东青岛 |
| 20050301 | 王敏  || 1989-12-23 00:00:00 |    江苏苏州 |
| 20050202 | 张立  || 1988-08-25 00:00:00 |    河北唐山 |
+----------+-------+------+---------------------+----------+
4 rows in set

你可能感兴趣的:(数据库,网络,运维,数据库,database)