文章詳情頁
sql查詢給表起別名要點小結(涉及嵌套查詢)
瀏覽:198日期:2023-03-12 15:25:16
目錄
- 可以通過空格或者as給表起別名
- 簡單查詢中使用別名
- 復雜查詢中使用別名
- 總結
可以通過空格或者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查詢給表起別名要點(涉及嵌套查詢)的文章就介紹到這了,更多相關sql查詢給表起別名內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!
標簽:
Oracle
排行榜
