SQL查詢_基本查詢
select 用于指定查詢所獲得的結(jié)果列夜矗,from 指定查詢的數(shù)據(jù)源妆偏,數(shù)據(jù)源可以是一個表我磁,也可以是一個臨時記錄集合圃阳,若from后面有多個數(shù)據(jù)源厌衔,這些數(shù)據(jù)源經(jīng)實現(xiàn)笛卡爾積,即第一個數(shù)據(jù)源的每條記錄與第二個數(shù)據(jù)源中的所有記錄組合捍岳,最終形成新的數(shù)據(jù)源
如:select * from employee,hh;
where用來過濾數(shù)據(jù)源富寿,distinct 獲得唯一性記錄,可以是單個列锣夹,也可以是多列組合
一页徐、查詢語法
select [distinct] 字段名1,……|* from 表名 where[查詢條件];
1.1、查詢表中所有字段
select * from 表名;
1.2银萍、查詢表中指定字段
select 字段1,字段2,…… from 表名;
1.3变勇、給字段設(shè)置別名
select 字段名 as ?新字段名 from 表名;(as可以省略)
二、運算符
算數(shù)運算符(+贴唇,-搀绣,*,/)
比較運算符(>戳气,>=链患,<,<=瓶您,<>)
邏輯運算符(and麻捻,or,not)
select * from employee where emp_salary is not null;
select * from employee where not(emp_salary=5000);
備注:not加在表達式前三呀袱、模糊查詢(like)
通配符:下劃線(_)贸毕、百分號(%)
_:代替一個字符select * from employee where emp_name like '張_';
%:代替0到多個字符select * from employee where emp_name like '張%';
四、范圍查詢
4.1压鉴、between……and(主要針對數(shù)值)
select * from employee where emp_salary between 1000 and 6000;(包含1000和6000)
備注:between……and 包含起始數(shù)據(jù)4.2崖咨、in(主要針對對象)
select * from employee where emp_name in('張三','李四');
五、對查詢結(jié)果進行排序(order by)
語法:select……from 表名 [where……] order by 字段1 desc/asc,字段2 desc/asc,……?(desc:降序油吭,asc:升序)
select * from employee order by emp_name desc;
select * from employee order by emp_name desc,emp_salary asc;
備注:可以按多個字段進行排序击蹲,字段1相等的情況下再字段2排序六署拟、對記錄集合進行分組(group by)
一旦使用了分組,select 語句的真實?操作目標為各個分組數(shù)據(jù)歌豺,每次循環(huán)處理的也是各個分組推穷,而不是單條記錄
語句:select distinct emp_department,avg(emp_salary) from employee group by emp_department;
EMP_DEPARTMENT ? ? ? AVG(EMP_SALARY)
-------------------- ----------------------
項目部 ? ? ? ? ? ? ? 5500
工程部 ? ? ? ? ? ? ? 4550設(shè)計部 ? ? ? ? ? ? ? 5000
七、having子句
having子句是針對group by 子句形成的分組之后的結(jié)果集的過濾
語句:
select distinct emp_department,avg(emp_salary) from employee group by emp_department having avg(emp_salary)>=5000 order by avg(emp_salary);
結(jié)果:
EMP_DEPARTMENT ? ? ? AVG(EMP_SALARY)
-------------------- ----------------------
設(shè)計部 ? ? ? ? ? ? ? 5000項目部 ? ? ? ? ? ? ? 5500