標籤:
4.1笛卡爾積
select 姓名,工資,城市 from 職工,倉庫
倉庫5條記錄,職工表18條記錄,結果18*5=90條記錄。
職工表18個員工,倉庫表5個倉庫,即5個職工所在的城市,若要顯示職工的姓名、工資及所在城市資訊,結果應該為18條記錄:
select 姓名,工資,城市 from 職工,倉庫 where 職工.倉庫號=倉庫.倉庫號
4.2帶有運算子的多表查詢
顯示工資不在1500~2000之間,並且城市為空白的職工姓名、工資及所在城市資訊:
select 姓名,工資,城市, from 職工,倉庫 where 職工.倉庫號=倉庫.倉庫號and not(工資 between 1500 and 2000) and 城市 is null
4.3帶有統計函數的多表查詢
顯示職工的姓名、工資、工資與平均工資之差及銷售金額資訊:
select 姓名,工資,工資-(select avg(工資) from 職工) as 與平均工資的差,金額 from 職工,訂購單 where 職工.職工號=訂購單.職工號
4.4帶有謂詞的多表查詢
顯示已有職工的倉庫資訊:
/*利用謂詞IN實現*/
select * from 倉庫 where 倉庫號in(select 倉庫號 from 職工)
/*利用謂詞exists實現*/
select * from 倉庫 where exists (select * from 職工 where 倉庫號=倉庫.倉庫號)
4.5帶有排序和分組的多表查詢
顯示wh1或wh2倉庫中,工資不大於職工zg16的工資的職工資訊,並要求職工姓名不含有“平”字,然後按工資從低到高顯示:
select * from 職工 where 工資<=(select 工資 from 職工 where 職工號=’zg16’) and 姓名 not like ‘%平%’ and 倉庫號 in(‘wh1’,’wh2’) order by 工資
顯示同職工的姓名、平均銷售金額和最大銷售金額資訊,條件是平均銷售金額大於10000,最大銷售金額大於16000:
select 姓名,avg(金額) as 平均金額,max(金額) as 最大金額 from 職工,訂購單 where 職工.職工號=訂購單.職工號 group by 姓名 having avg(金額)>10000 and max(金額)>16000
4.6多表巢狀查詢
顯示城市不在上海的職工資訊:
select * from 職工 where 倉庫號 in (select 倉庫號 from 倉庫 where 城市!=’上海’)
顯示不同倉庫職工的平均銷售金額和倉庫號資訊,條件是平均銷售金額大於15000或最大銷售金額小於18000、工資大於倉庫面積大於800的所有職工的平均工資:
select 倉庫號,avg(金額) as 平均金額 from 職工,訂購單 where 職工.職工號=訂購單.職工號 and 工資>(select avg(工資) from 職工 where 倉庫號 in(select 倉庫號 from 倉庫 where 面積>800) group by 倉庫號 having avg(金額)<15000 or max(金額)<18000
4.7超串連查詢
包括:內串連(inner join)、左串連(left join)、右串連(right join)、全串連(full join)
sql學習總結(4)——SQL多表查詢技術