子查詢就像使用普通的表一樣,被當作結果集的查詢語句被稱為子查詢。所有可以使用表的地方幾乎都可以使用子查詢來代替。
SELECT * FROM (SELECT * FROM student where sAge<30) as t
只有返回且僅返回一行、一列數據的子查詢才能當成單值子查詢。
子查詢返回的值不止一個。當子查詢跟隨在=、!=、<、<=、>、>=之后,或子查詢用作表達式時,這種情況是不允許的。
tips: select * from TblStudent where exists ( --子查詢的結果,要依賴于當前父查詢中當前行的tsClassid的結果。 select * from TblClass wheret ClassName='計算機軟件班' and tClassId=TblStudent.tsClassId ) |
如果子查詢是多行單列的子查詢,這樣的子查詢的結果集其實是一個集合。可以使用in關鍵字代替=號
select * from student where sClassId in ( select cId from class where cName='高一一班' or cName='高二一班' ) 等價于
Select* from student where exists(select * from class where (cName=‘高一一班’or cName=‘高二二班’)and class.cid=student.sclassid)