MySql資料庫--資料庫的新建以及基礎查詢
阿新 • • 發佈:2021-01-11
MySql資料庫的基本操作
//新建資料庫 creat database python_test charset=utf8; //使用資料庫 use python_test; //建立學生表 creat table students( id int unsigned primary key auto_increment not null, name varchar(20) default '', age tinyint unsigned default 0, height decimal(5,2), gender enum('男','女','保密') default '保密', cls_id int unsigned default 0, in_delete bit default 0 ); //新建課程classes表 create table classes( id int unsigned auto_increment primary key not null, name varchar(30) not null ); //插入資料 insert into students values (0,'小明',16,180.00,2,1,0), (0,'小明',18,180.00,2,1,0), (0,'小月月',18,180.00,2,2,1), (0,'彭于晏',29,185.00,1,1,0), (0,'劉德華',59,175.00,1,2,1), (0,'黃蓉',38,160.00,2,1,0), (0,'鳳姐',28,150.00,4,2,1), (0,'王祖賢',18,172.00,2,1,1), (0,'周杰倫',36,NULL,1,1,0), (0,'程坤',27,181.00,1,2,0), (0,'劉亦菲',25,166.00,2,2,0), (0,'金星',33,162.00,3,3,1), (0,'靜香',12,180.00,2,4,0), (0,'郭靖',12,170.00,1,4,0), (0,'周杰',34,176.00,2,5,0); //想classes表中插入資料 insert into classes values (1,"python_01期"),(1,"python_02期"); //查詢所有欄位 select * from students; //查詢指定欄位 select id,name from students; //使用as給欄位或者表起別名 select id as 序號,name as 姓名, gender as 性別 from students; select students.id,students,name,students,gender from students; select s.id,s.name,s.gerder from students as s; //去重 //在select後面列前面使用distinct可以消除重複的行 select distinct gender from students;
資料的條件查詢
使用where子句對錶中的欄位進行篩選,結果為true的行會出現在結果集合中 語法如下:
//select * from 表明 where 條件
select * from students where id=1;
where 後面支援多種運算子,進行條件的處理
- 比較運算子
- 邏輯運算子
- 模糊運算
- 範圍查詢
- 空判斷
比較運算子
/* 等於:= 大於:> 大於等於:>= 小於:< 小於等於:<= 不等於:!= 或者<> */ //查詢編號大於3的學生 select * from students where id>3; //查詢博鰲好不大於4的學生 select * from studemts where id<=4; //查詢姓名不是黃蓉的的學生 select * from students where name<>'黃蓉' //查詢沒被刪除的學生 sleect * from students where is_delect=0
邏輯運算子
/*
and
or
not
*/
//插敘編號大於3的女學生
select * from students where id>3 and gender=0;
//查詢編號小於4或者沒被刪除的學生
select * from students where id<4 or id_delect=0;
模糊查詢
/*
like
% 表示任意多個任意字元
_表示一個任意字元
rlike 正則匹配
*/
//查詢姓黃的學生 select * from students where name like '黃%'; //查詢姓黃並且名只有一個字的學生 select * from students where name like '黃_'; //查詢姓黃或者名字叫靖的同學 select * from steudnets where name like '黃%' or name like '%靖';
範圍查詢
in表示在一個非連續的範圍內
between … and … 表示在一個連續的範圍內
//查詢編號是1,3,6的學生
select * from students where id in (1,3,6);
//查詢編號是3到8的學生
select * from students where id between 3 and 8;
//查詢編號是3到8的男生
select * from srtudents where (id between 3 and 8) and gender=1;
空判斷
null 與 ’ '是不同的
判斷空 is null
// 查詢沒有填寫身高的學生
select * from students where height is null;
//判斷非空用is not null
//查詢填寫了身高的學生
select * from students where height is not null;
//查詢填寫了身高的男生
select * from students where height is not null and gender=1;
優先順序
優先順序由高到低的順序為 小括號,not,比較運算子,邏輯運算子
and 比or 先運算,如果同時出現並且希望先運算or,需要結合小括號使用!
參考原文連結:https://blog.csdn.net/weixin_42250835/article/details/90370483