sql查詢給表起別名要點(diǎn)小結(jié)(涉及嵌套查詢)
目錄
- 可以通過空格或者as給表起別名
- 簡單查詢中使用別名
- 復(fù)雜查詢中使用別名
- 總結(jié)
可以通過空格或者as給表起別名
但是注意如果操作的數(shù)據(jù)庫是Oracle的話,只能使用空格,as不符合Oracle的語法。
舉個(gè)栗子
簡單查詢中使用別名
select * from student s where s.id = "10";
在簡單的查詢中使用別名,一般沒有特別需要注意的地方,要做的操作少
復(fù)雜查詢中使用別名
題目概要:有三個(gè)表格,student(sno,sname,ssex,sbirthday,class)
score(sno,cno,degree)
course(cno,cname,tno)
查詢選修“3-105”課程的成績高于“109”號同學(xué)成績的所有同學(xué)的記錄。
答案:
select * from (select s.sno,s.sname,s.ssex,s.sbirthday,s.class, sc.degree,c.cno,c.cname,c.tno from student s , course c ,score sc where s.sno = sc.sno and c.cno = sc.cno) ss where ss.cno = "3-105" and ss.degree >( select degree from score where sno = "109" and cno = "3-105");
可以看到,為了方便操作,我們重新定義了一個(gè)表格ss,這個(gè)表格是一個(gè)大表格同時(shí)包含了,以上三個(gè)表中的內(nèi)容。但是要注意以下幾點(diǎn),不然容易出錯
要全部顯示新定義表格的值時(shí),不能直接使用*
比如聲明的答案中如果改為
select * from (select * from student s , course c ,score sc where s.sno = sc.sno and c.cno = sc.cno) ss where ss.cno = "3-105" and ss.degree >( select degree from score where sno = "109" and cno = "3-105");
命令行會顯示列未明確定義,因?yàn)槲覀円F(xiàn)在指定的列作為一個(gè)新的表,但是有些列的列名是重復(fù)的,我們需要指定其中的一個(gè)。
在嵌套查詢語句中無法使用新創(chuàng)的表,因?yàn)榍短撞樵兝锩娴拇a是一個(gè)完整的執(zhí)行段,會從頭開始運(yùn)行?反正在里面調(diào)用會報(bào)錯
select * from (select * from student s , course c ,score sc where s.sno = sc.sno and c.cno = sc.cno) ss where ss.cno = "3-105" and ss.degree >( select degree from ss where sno = "109" and cno = "3-105");
這段SQL里面在where里面的子查詢使用了ss新表,編譯會顯示表或視圖不存在錯誤。
總結(jié)
到此這篇關(guān)于sql查詢給表起別名要點(diǎn)(涉及嵌套查詢)的文章就介紹到這了,更多相關(guān)sql查詢給表起別名內(nèi)容請搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
