本文目錄一覽:
- 1、數據庫查詢 查詢“001”課程比“002”課程成績高的所有學生的學號
- 2、在數據庫中如何使用sql語句查詢:修了a12課程,且成績高於此課程的平均成績的學生的姓名和成績?急
- 3、數據庫 查詢數據結構課程最高分同學的學號、姓名、平均成績、選課門數
數據庫查詢 查詢“001”課程比“002”課程成績高的所有學生的學號
分析如下:
–1select SC1.S# from SC SC1 JOIN SC SC2 ON SC1.S#=SC2.S#
WHERE SC1.C#=’001′ AND SC2.C#=’002′ AND SC1.scoreSC2.score
–2select S#,AVG(score)
平均成績 from SC group by S#
having AVG(score)60 –3select Student.S#,
Sname,COUNT(*) 選課數,SUM(score) 總成績
from Student JOIN SC on Student.S#=SC.S#
group by Student.S#,Sname
擴展資料:
數據庫操作的注意事項
1、對查詢進行優化,要盡量避免全表掃描,首先應考慮在 where 及 order by 涉及的列上建立索引。
2、應盡量避免在 where 子句中對字段進行 null 值判斷,否則將導致引擎放棄使用索引而進行全表掃描,如:select id from t where num is null
最好不要給數據庫留NULL,儘可能的使用 NOT NULL填充數據庫.
備註、描述、評論之類的可以設置為 NULL,其他的,最好不要使用NULL。
不要以為 NULL 不需要空間,比如:char(100) 型,在字段建立時,空間就固定了, 不管是否插入值(NULL也包含在內),都是佔用 100個字符的空間的,如果是varchar這樣的變長字段, null 不佔用空間。
可以在num上設置默認值0,確保表中num列沒有null值,然後這樣查詢:select id from t where num = 0
3、應盡量避免在 where 子句中使用 != 或 操作符,否則將引擎放棄使用索引而進行全表掃描。
4、應盡量避免在 where 子句中使用 or 來連接條件,如果一個字段有索引,一個字段沒有索引,將導致引擎放棄使用索引而進行全表掃描,如:select id from t where num=10 or Name = ‘admin’
可以這樣查詢:
select id from t where num = 10
union all
select id from t where Name = ‘admin’
5、in 和 not in 也要慎用,否則會導致全表掃描,如:select id from t where num in(1,2,3)
對於連續的數值,能用 between 就不要用 in 了:select id from t where num between 1 and 3
很多時候用 exists 代替 in 是一個好的選擇:select num from a where num in(select num from b)
用下面的語句替換:select num from a where exists(select 1 from b where num=a.num)
6、下面的查詢也將導致全表掃描:select id from t where name like ‘%abc%’
若要提高效率,可以考慮全文檢索。
7、如果在 where 子句中使用參數,也會導致全表掃描。因為SQL只有在運行時才會解析局部變量,但優化程序不能將訪問計劃的選擇推遲到運行時;它必須在編譯時進行選擇。然 而,如果在編譯時建立訪問計劃,變量的值還是未知的,因而無法作為索引選擇的輸入項。
參考資料來源:百度百科:數據庫
在數據庫中如何使用sql語句查詢:修了a12課程,且成績高於此課程的平均成績的學生的姓名和成績?急
select 姓名,成績 from 表名 where a12=1 and 成績>(select avg(成績) from 表名)
數據庫 查詢數據結構課程最高分同學的學號、姓名、平均成績、選課門數
select t.sno,sname,avg(grade) as 平均分,count(cname) as 選課門數
from student t,sc c,course e
where t.sno=c.sno and c.cno=e.cno and t.sno=
(select top 1 t1.sno from student t1,sc c1,course e1 where t1.sno=c1.sno and c1.cno=e1.cno and e1.cname=’數據結構’ order by c1.grade desc)
group by t.sno,sname
先用子查詢 查出課程最高分的同學的學號
再根據學號得到平均分agv和選課門數 count
原創文章,作者:MRDC,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/137793.html