共計 1402 個字符,預計需要花費 4 分鐘才能閱讀完成。
這篇“SQL 查詢怎么給表起別名”文章的知識點大部分人都不太理解,所以丸趣 TV 小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“SQL 查詢怎么給表起別名”文章吧。
可以通過空格或者 as 給表起別名
但是注意如果操作的數據庫是 Oracle 的話,只能使用空格,as 不符合 Oracle 的語法。
舉個栗子
簡單查詢中使用別名
select *
from student s
where s.id = 10
在簡單的查詢中使用別名,一般沒有特別需要注意的地方,要做的操作少
復雜查詢中使用別名
題目概要:有三個表格,student(sno,sname,ssex,sbirthday,class)
score(sno,cno,degree)
course(cno,cname,tno)
查詢選修“3-105”課程的成績高于“109”號同學成績的所有同學的記錄。
答案:
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
可以看到,為了方便操作,我們重新定義了一個表格 ss,這個表格是一個大表格同時包含了,以上三個表中的內容。但是要注意以下幾點,不然容易出錯
要全部顯示新定義表格的值時,不能直接使用 *
比如聲明的答案中如果改為
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
命令行會顯示列未明確定義,因為我們要現在指定的列作為一個新的表,但是有些列的列名是重復的,我們需要指定其中的一個。
在嵌套查詢語句中無法使用新創的表,因為嵌套查詢里面的代碼是一個完整的執行段,會從頭開始運行?反正在里面調用會報錯
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 新表,編譯會顯示表或視圖不存在錯誤。
以上就是關于“SQL 查詢怎么給表起別名”這篇文章的內容,相信大家都有了一定的了解,希望丸趣 TV 小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注丸趣 TV 行業資訊頻道。