sql語句(Oracle和mysql)的注意事項
我們在平時寫sql語句的時候很容易忽視一些細節問題,而且在Oracle和mysql中sql語句也是有很多的不同之處,這些我們都需要注意,下面我就把平時比較容易忽視的幾個點列出來。
一:分頁
mysql 分頁:select * form 表名 limit m,n;
Oracel中分頁:
(1)SELECT * FROM( SELECT A., ROWNUM RN FROM (SELECT FROM TABLE_NAME) A WHERE ROWNUM <= 40) WHERE RN >= 21
(2)SELECT * FROM( SELECT A., ROWNUM RN FROM (SELECT
(3)select * from(select a.,rownum rn from (select from t_articles) a where rownum < 11) where rn>5
或: select * from ( select t.*,rownum rn from tb_user t where rownum < 4 ) where rn > 1
二:分組
select service_name,url, count() from tb_interface_config group by service_name,url having count(
select count(distinct deptno) from user;
注意1:分組時前面有幾個欄位group by後也要有幾個欄位。
注意2:使用count統計行數的時候,count()括號裡面的可以寫*或者任意的數字,結果都是一樣的。
注意3:所有聚集函式都可以使用distinct
注意4: 一張表,一旦分組 完成後,查詢後只能得到組相關的資訊。
注意5:order by 和group by 前面where可有可無,而且前面不能加and。
三:where和having
select Student.S#,Student.Sname from Student,SC where Student.S#=SC.S# group by Student.S#,Student.Sname having count(C#) <(select count(C#) from Course);
四:外連線
select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where …..
五: 當欄位值為null的時候把值賦為0;
select S#,avg(isnull(score,0)) from SC where S# in (select S# from SC where score <60 group by S# having count(*)>2)group by S#;
六:in ,between,like
select * from table1 where field1 like ’%value1%’ —like的語法很精妙,查資料!
select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3)
select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)
select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between 數值1 and 數值2
SC(S#,C#,score) 成績表
七:統計每門課程的學生選修人數(超過10人的課程才統計)。要求輸出課程號和選修人數,查詢結果按人數降序排列
,查詢結果按人數降序排列,若人數相同,按課程號升序排列
select C# as 課程號,count() as 人數 from sc group by C# order by count(
八:查詢前幾
在SQL裡。一般要選都是第一條都是
select top 2 a,b from table order by c.
在 ORACLE裡
select * from (select a,b from table order by c) where rownum<=2; 先排序,再取前幾位,注意優先順序的問題。
注意1:TOP不能在Oracle中使用。
注意2:DISTINCT 必須放在第一個引數。
九:使用一個表進行聯查時,必須要用到distinct,不然查詢的結果是有兩個一樣的資料(不等號 a. != ; b. <>)
查詢不同課程成績相同的學生的學號、課程號、學生成績
select distinct A.S#,a.score from SC A ,SC B where A.Score=B.Score and A.C# <>B.C# ;
十: CONVERT() 函式是把日期轉換為新資料型別的通用函式。
CONVERT() 函式可以用不同的格式顯示日期/時間資料。
十一: sql 查分數段人數
select count(case 分數字段 when 100 then 1 end) as [滿分],
count(case when 分數字段 between 90 and 99 then 1 end) as[90-99分],
count(case when 分數字段 between 80 and 89 then 1 end) as[80-89分],
count(case when 分數字段 between 70 and 79 then 1 end) as[70-79分],
count(case when 分數字段<70 then 1 end) as[70分以下]
from 學生分數表
SELECT SC.C# as 課程ID, Cname as 課程名稱
,SUM(CASE WHEN score BETWEEN 85 AND 100 THEN 1 ELSE 0 END) AS [100 - 85]
,SUM(CASE WHEN score BETWEEN 70 AND 85 THEN 1 ELSE 0 END) AS [85 - 70]
,SUM(CASE WHEN score BETWEEN 60 AND 70 THEN 1 ELSE 0 END) AS [70 - 60]
,SUM(CASE WHEN score < 60 THEN 1 ELSE 0 END) AS [60 -]
FROM SC,Course where SC.C#=Course.C# GROUP BY SC.C#,Cname;