1. 程式人生 > >MySQL數據庫基本用法-查詢

MySQL數據庫基本用法-查詢

數據庫基本 span 括號 判空 分隔 between 用法 select 查詢

查詢的基本語法
select * from 表名;
  1. from關鍵字後面寫表名,表示數據來源於是這張表
  2. select後面寫表中的列名,如果是*表示在結果中顯示表中所有列
  3. 在select後面的列名部分,可以使用as為列起別名,這個別名出現在結果集中
  4. 如果要查詢多個列,之間使用逗號分隔

 

消除重復行

在select後面列前使用distinct可以消除重復的行
select distinct gender from students;

  

條件

  1. 使用where子句對表中的數據篩選,結果為true的行會出現在結果集中
  2. 語法如下:
select * from 表名 where 條件;

  

比較運算符

  • 等於=
  • 大於>
  • 大於等於>=
  • 小於<
  • 小於等於<=
  • 不等於!=或<>
  • 查詢編號大於3的學生
select * from students where id>3;
  • 查詢編號不大於4的科目
select * from subjects where id<=4;

  

  • 查詢姓名不是“黃蓉”的學生
select * from students where sname!=‘黃蓉‘;

  

  • 查詢沒被刪除的學生
select * from students where isdelete=0;

  

邏輯運算符

  • and
  • or
  • not
  • 查詢編號大於3的女同學
select * from students where id>3 and gender=0;

  

  • 查詢編號小於4或沒被刪除的學生
select * from students where id<4 or isdelete=0;

  

模糊查詢

  • like 關鍵字
  • %表示任意多個任意字符
  • _表示一個任意字符
  • 查詢姓黃的學生
select * from students where sname like ‘黃%‘;

  

  • 查詢姓黃並且名字是一個字的學生
select * from students where sname like ‘黃_‘;

  

  • 查詢姓黃或叫靖的學生
select * from students where sname like ‘黃%‘ or sname like ‘%靖%‘;

  

範圍查詢

  • in表示在一個非連續的範圍內
  • 查詢編號是1或3或8的學生
select * from students where id in(1,3,8);

  

  • between ... and ...表示在一個連續的範圍內
  • 查詢學生是3至8的學生
select * from students where id between 3 and 8;

  

  • 查詢學生是3至8的男生
select * from students where id between 3 and 8 and gender=1;

  

空判斷

  • 註意:null與‘‘是不同的
  • 判空is null
  • 查詢沒有填寫地址的學生
select * from students where hometown is null;

  

  • 判非空is not null
  • 查詢填寫了地址的學生
select * from students where hometown is not null;

  

  • 查詢填寫了地址的女生
select * from students where hometown is not null and gender=0;

  

優先級

  • 小括號,not,比較運算符,邏輯運算符
  • and比or先運算,如果同時出現並希望先算or,需要結合()使用

MySQL數據庫基本用法-查詢