select語句使用詳解
select語句是基礎(chǔ)操作中比較復(fù)雜的部分,我們單拿出來詳細(xì)解析一下。還是以上一篇文章里的student表為例。
- select * from student:查詢student表中所有記錄。
-
create table stu2 select * from student:創(chuàng)建一個stu2表,內(nèi)容與student是一樣的,但注意,主鍵值是不一樣的。
因此我們就可以使用alter table stu2 modify id int not null auto_increment primary key這個SQL語句來重新定義主鍵'id'。
投影和選擇:
-
投影:select name,age from stu2。選擇某幾列作為查詢內(nèi)容,這叫做投影。
select name as 姓名,age as 年齡 from stu2:對列投影進(jìn)行重命名。 - 選擇:select * from stu2 where id>3。選擇某幾行作為查詢內(nèi)容,這叫做選擇。
DISTINCT:去掉重復(fù)行。
- select DISTINCT name,age,sex from stu2:去掉重復(fù)的name,age,sex段數(shù)據(jù)。
- 條件。select * from stu2 where name='張三' and id>3:where的選擇。and表示與,也可以用or表示或。
- select * from stu2 where id in(3,5,6):表明顯示id為3,5,6的三行數(shù)據(jù)。
- select * from stu2 where id in(select id from stu2 where sex = 'M':子查詢。子查詢中表示表中id所有為性別為M的id顯示出來并作為條件。那么外層表示使用這些id顯示在表上(當(dāng)然此句只是為了嵌套,并不需要寫的這么麻煩)。
- select * from stu2 where sex is null or birth is null:判斷為空時必須使用is,而不是'='。
- select * from stu2 where id between 2 and 5:數(shù)據(jù)條件在2和5之間。
假設(shè)現(xiàn)在數(shù)據(jù)庫dep和emp中的數(shù)據(jù)如下所示:(emp中dep_id為dep外鍵)

-
select count() from dep:統(tǒng)計(jì)dep表總共有多少行。
此時注意:如果count(列名),那么返回的行數(shù)是不包含對行中參數(shù)有NULL的統(tǒng)計(jì)的。 - select max(age) from emp:統(tǒng)計(jì)emp表中age最大的行。
- select avg(age) from emp:統(tǒng)計(jì)平均值。
- select dep_id,count(dep_id) from emp group by dep_id:group by的作用:看上圖,我們對dep_id這一列的元素進(jìn)行分組,即dep_id為1,2,3三個數(shù)進(jìn)行分組,求出每一個dep_id總共占幾行,select后面的dep_id表示我現(xiàn)在要顯示的是哪一列。如果沒有g(shù)roup by,那么我們不能按dep_id的數(shù)字不同來分別求行數(shù)。

- select dep_id,count(dep_id) from emp group by dep_id WITH ROLLUP:對結(jié)果再匯總。

select dep_id,count(dep_id) from emp group by dep_id having count(dep_id)>1:having相當(dāng)于條件過濾,相當(dāng)于where,但注意,在group by后面我們不能用where,只能用having。
select * from emp order by age asc(desc):按年齡(age)升序(降序)排列。

select * from emp order by sex asc,dep_id asc:先根據(jù)第一個條件升序排列,再根據(jù)第二個條件升序排列。
select * from emp limit 3:只想要三行數(shù)據(jù)。
select * from emp limit 2,3:分頁查詢。從第3條數(shù)據(jù)開始。select e.id,d.name as dname,e.name as ename,e.age,e.sex from dep d,emp e where d.id=e.dep_id;

語句釋義:from后面的dep和emp都被重命名為d和e,然后select的列有e.id,dname,ename,e.age,e.sex。條件過濾為d.id=e.dep_id。
上面的SQL語句被稱為多表查詢。
那么現(xiàn)在我們在dep中插入一個NULL值的數(shù)據(jù)。
insert into dep values(null,'人力資源')。
LEFT JOIN與RIGHT JOIN語句(外聯(lián)查詢)
1.LEFT JOIN,左外連接,以左表為基準(zhǔn),到右表找匹配的數(shù)據(jù),找不到匹配的用NULL補(bǔ)齊,顯示左表的全部記錄及右表符合連接條件的記錄。
select * from t1 left join t2 on t1.id=t2.id;
2.RIGHT JOIN,右外連接,與左外連接呈對稱形式。
注意:如果我們此時select *,那么若t1和t2兩個表中字段不同,則會將所有字段顯示出來,但基準(zhǔn)依舊是某一個表,如t1里id為1和2,t2里id為1和3,那么上面左外聯(lián)語句就會顯示所有id為1和2的結(jié)果,而不會顯示t2中id為3的結(jié)果。
INNER JOIN語句(內(nèi)聯(lián)查詢)
內(nèi)聯(lián)查詢:只顯示符合連接條件的記錄。
select * from t1 inner join t2 on t1.id=t2.id;
這條SQL語句意為:搜索所有列,找出符合t1.id=t2.id條件的記錄,匹配的顯示不匹配的不現(xiàn)實(shí)(即不會用NULL補(bǔ)齊)