select格式:
SELECT [ ALL | DISTINCT ] <欄位運算式1[,<欄位運算式2[,…]
FROM <表名1>,<表名2>[,…]
[WHERE <篩選擇條件運算式>]
[GROUP BY <分組運算式> [HAVING<分組條件運算式>]]
[ORDER BY <欄位>[ASC | DESC]]
語句說明:
[]方括弧為可選項
[GROUP BY <分組運算式> [HAVING<分組條件運算式>]]
指將結果按<分組運算式>的值進行分組,該值相等的記錄為一組,帶【HAVING】
短語則只有滿足指定條件的組才會輸出。
[ORDER BY <欄位>[ASC | DESC]]
顯示結果要按<欄位>值升序或降序進行排序
sql各子句的執行順序:
1. FROM
2. WHERE
3. GROUP BY
4. HAVING
5. SELECT
6. ORDER BY
練習:
1:表hkb_test_sore取出成績sore前5名的記錄,
2:取第5名的記錄
1,答案select a.sore_id, a.sore
from (select * from hkb_test_sore order by sore desc) a
where rownum <=5
2,答案select a.sore_id, a.sore
from (select * from hkb_test_sore order by sore desc) a
where rownum <=5
minus
select a.sore_id, a.sore
from (select * from hkb_test_sore order by sore desc) a
where rownum <=4;
3:查詢兩個分數一樣的記錄
select *
from hkb_test_sore a
where a.sore = (select sore
from hkb_test_sore a
group by a.sore
having count(a.sore) = 2);
union,union all,intersect,minus的區別:
SQL> select * from hkb_test2;
X Y
---- -----
a 1
b 2
c 3
g 4
SQL> select * from hkb_test3;
X Y
---- -----
a 1
b 2
e 3
f 4
SQL> select * from hkb_test2;
X Y
---- -----
a 1
b 2
c 3
g 4
SQL> select * from hkb_test3;
X Y
---- -----
a 1
b 2
e 3
f 4
SQL> select * from hkb_test2
2 union
3 select * from hkb_test3;
X Y
---- -----
a 1
b 2
c 3
e 3
f 4
g 4
6 rows selected
SQL> select * from hkb_test2
2 union all
3 select * from hkb_test3;
X Y
---- -----
a 1
b 2
c 3
g 4
a 1
b 2
e 3
f 4
8 rows selected
SQL> select * from hkb_test2
2 intersect
3 select * from hkb_test3;
X Y
---- -----
a 1
b 2
SQL> select * from hkb_test2
2 minus
3 select * from hkb_test3;
X Y
---- -----
c 3
g 4