SQL學習隨筆-數據表數據操作

1.數據的增加

  • 全列插入:值和表的字段順序一一對應
    insert into students values (1,'張三',20,1,1);
  • 指定列插入:值和列一一對應
    insert into students (name,gender,class_id) values ('大喬',4,2);
  • 多行插入,批量插入:values間用 , 隔開
    insert into students (name,gender) values ('小喬',4),('周瑜',2);

2.數據的刪除
delete from students where id = 2; # 用where做限定條件

3.數據的更改—update
update students set age = 26 where id = 2;

4.數據的查詢—select

  • 查詢所有字段數據
    select * from students;
  • 查詢指定字段數據
    select name,gender from students; # 多字段用逗號隔開
  • 使用 as 給字段起別名(用得少,僅作用於當前語句)
    select name as 名字, gender as 性別 from students;
    select name 名字 ,gender 性別 from students;
  • 跨表查詢
    select students.name, classes.name from students,classes;
  • 使用 as 給表起別名(當表的名字很長,可以使用)
    select s.name,s.gender from students as s;
    select students.name, students.gender from students;
  • 消除重複行—distinct
    select gender from students; # 查詢班級學生的性別
    select distinct gender from students; # 查詢班級有多少種性別
    select distinct id,gender from students; 多個字段,只有多列的結果完全相同才能去重
  • 條件查詢—where
    # 1.查詢年齡大於18的數據
    select * from students where age > 18;
    # 2.查詢18歲以上的女性,and邏輯運算
    select * from students where age > 18 and gender = '女';
    # 3.18歲以上或者身高超過180(包含)以上的數據,or邏輯運算
    select * from students where age > 18 or height >= 180;
    # 4.年齡不是18歲的學生的數據,not邏輯運算
    select * from students where age != 18;
    select * from students where not age = 18;
  • 模糊查詢—like 接字符串,%表示任意字符可有可無(0個或者多個), _表示任意一個字符
    # 1.查詢姓名中以 "小" 開始的名字
    select * from students where name like "小%";
    # 2.查詢姓名中名字中包含 "傑"的名字
    select * from students where name like "%傑%";
    # 3.查詢有2個字的名字
    select * from students where name like"__";
    # 4.正則表達式(待補充)
    select * from students where name rlike ".*傑$";
  • 範圍查詢
    # 1.in 表示在一個非連續的範圍內
    select * from students where age in(18,34);
    # 2.not in 表示不在一個非連續的範圍內,取反操作
    select * from students where age not in (18,34);
    # 3.between ... and ...表示在一個連續的範圍內 ,兩邊都會包含
    select * from students where age between 18 and 34;
    # 4.not between ... and ...表示不在一個連續的範圍內
    select * from students where age not between 18 and 34;
    select * from students where not age between 18 and 34;
    # 5.空判斷 null 不能夠使用比較運算符
    select * from students where height is null;
    select * from students where height ="";
    # 6.不爲空的判斷
    select * from students where height is not null;
    select * from students where not height is null;
  • 排序查詢
    order by 字段 默認就是升序排序 asc 可以省略
    asc從小到大排列,即升序; desc從大到小排序,即降序
    # 1.查詢年齡在18到34歲之間的男性,按照年齡從小到大排序
    select * from students where age between 18 and 34 and gender = '男' order by age asc;
    # 2.order by 多個字段 order by age asc, height desc
    # 查詢年齡在18到34歲之間的女性,身高從高到矮排序, 如果身高相同的情況下按照年齡從小到大排序
    select * from students where age between 18 and 34 and gender = 2 order by height desc,age asc;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章