1、創建表
create table 表名稱(
字段1 數據類型 not null auto_increment comment '第一個字段',
字段2 數據類型 not null default '男' auto_increment comment '第2個字段',
primary key(sno)
)engine=innodb default charset utf8 comment "學生表";
注意:comment設置字段備註,not null 設置字段不允許爲空,default 設置字段的默認值
auto_increment 自動增長
primary key(字段) 設置爲主鍵
//例如 create table student( sno int auto_increment comment '學號', sname varchar(20) charset utf8 collate utf8_general_ci not null, ssex char(4) charset utf8 collate utf8_general_ci default '男', primary key(sno) )engine=innodb default charset utf8;
注意:not null 設置該字段不能爲空,default設置該字段的默認值
primary key 該字段的值不允許重複
auto_increment 自增 只適用於整型(int、tinyint、bigint等
2、表中插入數據
單條插入語法
insert into 表名稱(字段1,字段2....) values(值1,值2....)
例如:
insert into student(sno,sname,ssex) values('1','小紅','女');
插入多條語法
insert into 表名稱(字段1,字段2....)values
(值1,值2....),
(值11,值22...)
例如:
insert into student(sno,sname,ssex) values(值1,值2....),(值11,值22....);
3、單表的查詢語句(select)
select * from 表名稱; //查詢表中所有數據,*表示查詢所有字段
例如:select * from student;
select 字段1,字段2..... from 表名稱 //查詢表中指定字段的所有數據
where條件查詢
單條件查詢
例如:select sname,s_birth1 from student where s_sex='男';//查詢s_sex='男'的sname,s_birth1字段的數據
多條件查詢
條件與條件之間使用and 或者 or連接,and與or同時出現在條件中時,先and後or;最好使用小括號來確定執行順序
例如:select sname,s_birth1 from student where s_sex='男' and s_age=26; //查詢s_sex='男'並且s_age=26
範圍查詢
< > <= >= != <>
例如:select * from student where s_age<>26;
between and 閉合區間,包括前包括後,相當於 >= and <=
例如:select * from student where s_age between 20 and 26;
in() 表示某字段的值包含小括號裏邊的數據
例如:select * from student where s_age in(20,22,26);//查詢student表中s_age字段的值爲20,22,26的數據
not in()
例如:select * from student where s_age not in(20,22,26);//查詢student表中s_age字段的值不是20,22,26的數據
like 模糊查詢
select * from student where s_name like '%紅%';
not like 模糊查詢
例如: select * from student where sname like '%紅%' and sname not like '%紅' and sname not like '紅%';
說明:條件自左向右執行
'%' 表示匹配任意多個字符 '_' 表示匹配一個字符
4、表中數據的修改(操作需謹慎)
update 表名稱 set 字段名=新值 where 條件;
例如:update student1 set s_sex='女' where sname='小紅';//修改一個字段
update student1 set s_sex='女',s_age=30 where sname='小紅';//一次修改多個字段時用逗號隔開
5、刪除表中的數據(操作需謹慎)
delete from 表名稱 where 條件;
例如:delete from student1 where s_no=5;