MySQL-基本查詢語句及方法,連表和子查詢


一、基本查詢語句

create table emp(
  id int not null unique auto_increment,
  name varchar(20) not null,
  sex enum('male','female') not null default 'male', #大部分是男的
  age int(3) unsigned not null default 28,
  hire_date date not null,
  post varchar(50),
  post_comment varchar(100),
  salary double(15,2),
  office int, #一個部門一個屋子
  depart_id int
);

#插入記錄
#三個部門:教學,銷售,運營
insert into emp(name,sex,age,hire_date,post,salary,office,depart_id) values
('jason','male',18,'20170301','張江第一帥形象代言',7300.33,401,1), #以下是教學部
('egon','male',78,'20150302','teacher',1000000.31,401,1),
('kevin','male',81,'20130305','teacher',8300,401,1),
('tank','male',73,'20140701','teacher',3500,401,1),
('owen','male',28,'20121101','teacher',2100,401,1),
('jerry','female',18,'20110211','teacher',9000,401,1),
('nick','male',18,'19000301','teacher',30000,401,1),
('sean','male',48,'20101111','teacher',10000,401,1),

('歪歪','female',48,'20150311','sale',3000.13,402,2),#以下是銷售部門
('丫丫','female',38,'20101101','sale',2000.35,402,2),
('丁丁','female',18,'20110312','sale',1000.37,402,2),
('星星','female',18,'20160513','sale',3000.29,402,2),
('格格','female',28,'20170127','sale',4000.33,402,2),

('張野','male',28,'20160311','operation',10000.13,403,3), #以下是運營部門
('程咬金','male',18,'19970312','operation',20000,403,3),
('程咬銀','female',18,'20130311','operation',19000,403,3),
('程咬銅','male',18,'20150411','operation',18000,403,3),
('程咬鐵','female',18,'20140512','operation',17000,403,3)
;

#ps:如果在windows系統中,插入中文字符,select的結果為空白,可以將所有字符編碼統一設置成gbk
前期准備

  1.select  # 拿出篩選出來的數據中的某些字段

  2.from  # 確定到底是哪張表

  3.where  # 約束條件,對整體數據進行初步篩選(放在分組前)

# 1.查詢id大於等於3小於等於6的數據
select id,name from emp where id >= 3 and id <= 6;
select *  from emp where id between 3 and 6;  

# 2.查詢薪資是20000或者18000或者17000的數據
select * from emp where salary = 20000 or salary = 18000 or salary = 17000;
select * from emp where salary in (20000,18000,17000);  # 簡寫

# 3.查詢員工姓名中包含o字母的員工姓名和薪資
# 在你剛開始接觸mysql查詢的時候,建議你按照查詢的優先級順序拼寫出你的sql語句
"""
先是查哪張表 from emp
再是根據什么條件去查 where name like ‘%o%’
再是對查詢出來的數據篩選展示部分 select name,salary
"""
select name,salary from emp where name like '%o%';

# 4.查詢員工姓名是由四個字符組成的員工姓名與其薪資
select name,salary from emp where name like '____';
select name,salary from emp where char_length(name) = 4;

# 5.查詢id小於3或者大於6的數據
select *  from emp where id not between 3 and 6;

# 6.查詢薪資不在20000,18000,17000范圍的數據
select * from emp where salary not in (20000,18000,17000);

# 7.查詢崗位描述為空的員工名與崗位名  針對null不能用等號,只能用is
select name,post from emp where post_comment = NULL;  # 查詢為空!
select name,post from emp where post_comment is NULL;
select name,post from emp where post_comment is not NULL;
View Code

  4.group by  # 分組  

    4.1 聚合函數max、min、avg、sum、count在分組之后用,(若語句中無group by,則整個語句算一個組)

# 2.獲取每個部門的最高工資  
# 以組為單位統計組內數據>>>聚合查詢(聚集到一起合成為一個結果)
# 每個部門的最高工資
select post,max(salary) from emp group by post;
# 每個部門的最低工資
select post,min(salary) from emp group by post;
# 每個部門的平均工資
select post,avg(salary) from emp group by post;
# 每個部門的工資總和
select post,sum(salary) from emp group by post;
# 每個部門的人數
select post,count(id) from emp group by post;
View Code

    4.2 給字段起別名 :字段名 as '別名'

    4.3 嚴格模式下,分組后不能夠直接再插到單個數據信息,只能獲取到組名   

set global sql_mode="strict_trans_tables,only_full_group_by";
# 重新鏈接客戶端
select * from emp group by post;  # 報錯
select id,name,sex from emp group by post;  # 報錯
select post from emp group by post;  # 獲取部門信息
View Code

      所以可以用group_concat 

      不僅可以用來顯示除分組外字段,還有拼接字符串的作用。

# 3.查詢分組之后的部門名稱和每個部門下所有的學生姓名
# group_concat(分組之后用)不僅可以用來顯示除分組外字段還有拼接字符串的作用
select post,group_concat(name) from emp group by post;

select post,group_concat(name,"_SB") from emp group by post;

select post,group_concat(name,": ",salary) from emp group by post;

select post,group_concat(salary) from emp group by post;


# 4.補充concat(不分組時用)拼接字符串達到更好的顯示效果 as語法使用
select name as 姓名,salary as 薪資 from emp;
select concat("NAME: ",name) as 姓名,concat("SAL: ",salary) as 薪資 from emp;

# 補充as語法 即可以給字段起別名也可以給表起
select emp.id,emp.name from emp as t1; # 報錯  因為表名已經被你改成了t1
select t1.id,t1.name from emp as t1;
View Code

      小技巧:
        concat 就是用來幫你拼接數據 (concat(' : ',a,b,c ))
        concat 不分組情況下使用
        group_concat 分組之后使用

  5.having  # 對分組之后數據再進行一次正對性篩選(放在分組后)

    having的語法格式與where一致,只不過having是在分組之后進行的過濾,即where雖然不能用聚合函數,但是having可以!

1、統計各部門年齡在30歲以上的員工平均工資,並且保留平均工資大於10000的部門
select post,avg(salary) from emp
        where age >= 30
        group by post
        having avg(salary) > 10000;
# 如果不信你可以將having取掉,查看結果,對比即可驗證having用法!

#強調:having必須在group by后面使用
select * from emp having avg(salary) > 10000;  # 報錯
View Code

  6.distinct  # 去重

# 對有重復的展示數據進行去重操作
select distinct post from emp;
View Code

  7.order by  # 排序 

    默認是升序 asc
    也可以變成降序 desc

select * from emp order by salary asc; #默認升序排
select * from emp order by salary desc; #降序排

select * from emp order by age desc; #降序排

#先按照age降序排,在年輕相同的情況下再按照薪資升序排
select * from emp order by age desc,salary asc; 

# 統計各部門年齡在10歲以上的員工平均工資,並且保留平均工資大於1000的部門,然后對平均工資進行排序
select post,avg(salary) from emp
    where age > 10
    group by post
    having avg(salary) > 1000
    order by avg(salary)
    ;
View Code

 

  8.limit  # 限制數據的條數

    select * from emp limit 5;  # 只展示數據的五條
    select * from emp limit 5,5;  
    
    """
    當limit只有一個參數的時候  表示的是只展示幾條
    當limit有兩個參數的時候   第一個參數表示的起始位置 第二個參數表示從起始位置開始往后展示的條數
    
    """
View Code

  9、正則

    # 在編程中 只要看到reg開頭的 基本上都是跟正則相關

    select * from emp where name regexp '^j.*(n|y)$';

  

  select * from emp\G; 當表字段特別多時,結果的排版可能會出現混亂的現象 可以在查詢語句加\G來規范查詢結果

  ps:MySQL對大小寫不敏感

  執行順序:from→where→group by→having→select→distinct

 

二、連表

#建表
create table dep(
id int,
name varchar(20) 
);

create table emp(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') not null default 'male',
age int,
dep_id int
);

#插入數據
insert into dep values
(200,'技術'),
(201,'人力資源'),
(202,'銷售'),
(203,'運營');

insert into emp(name,sex,age,dep_id) values
('jason','male',18,200),
('egon','female',48,201),
('kevin','male',38,201),
('nick','female',28,202),
('owen','male',18,200),
('jerry','female',18,204)
;
建表

引子:

select * from emp,dep;  # 左表一條記錄與右表所有記錄都對應一遍>>>笛卡爾積

# 將所有的數據都對應了一遍,雖然不合理但是其中有合理的數據,現在我們需要做的就是找出合理的數據

# 查詢員工及所在部門的信息
select * from emp,dep where emp.dep_id = dep.id;
# 查詢部門為技術部的員工及部門信息
select * from emp,dep where emp.dep_id = dep.id and dep.name = '技術';
笛卡爾積

  1.so 將兩張表關聯到一起的操作,有專門對應的方法

    inner join    (內連接:只取兩張表有對應關系的記錄)

    left join  (左連接:在內連接的基礎上保留左表沒有對應關系的記錄)

    right join  (右連接:在內連接的基礎上保留右表沒有對應關系的記錄)

    union    (全連接:在內連接的基礎上保留左、右面表沒有對應關系的的記錄) 

      # 只要將左連接和右連接的sql語句 加一個union就變成全連接

      例:

      select *from emp left join dep on emp.emp_id = dep_id

      union

      select * from emp right join dep on emp.emp_id = dep.id;

 

三、子查詢

  即:將一個查詢語句的結果用括號括起來當作另外一個查詢語句的條件去用

# 1.查詢部門是技術或者人力資源的員工信息
"""
先獲取技術部和人力資源部的id號,再去員工表里面根據前面的id篩選出符合要求的員工信息
"""
select * from emp where dep_id in (select id from dep where name = "技術" or name = "人力資源");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM