練習 學生班級

2021-08-25 04:18:54 字數 2085 閱讀 5768

create table t_class(

c_id int primary key,

c_name varchar(10)

);insert into t_class values(1,'一班');

insert into t_class values(2,'二班');

insert into t_class values(3,'三班');

alter table 學生表 add  c_id int;

--流程

select *,0 as 人數 from t_class;

select *,

(select count(*) from 學生表 s

where s.c_id=c.c_id

) as 人數

from t_class c;

--迴圈:c.c_id為1,2,3,分別代入子查詢,子查詢再執行

--理解:

執行外部查詢

select * from t_class

c_id    c_name

1 一班

select count(*) from 學生表 s  where s.c_id=1

2 二班

select count(*) from 學生表 s  where s.c_id=2

3 三班

select count(*) from 學生表 s  where s.c_id=3

效率:非常低,應該盡量避免(使用表連線)

但是知識點(相關子查詢)是非常重要的!

子查詢不能單獨執行:

select count(*) from 學生表 s

where s.c_id=c.c_id

語法:查詢哪些班上沒有人

select *

from t_class c

where not exists(

select * from 學生表 s where s.c_id=c.c_id

)唯一乙個where後面不需要指明欄位的

子查詢中select的值沒有限制

select *

from t_class c

where not exists(

select 'x' from 學生表 s where s.c_id=c.c_id

)語法:

from 表1

where [not] exists

( select * from 表2 where 表2.id=表1.id)

流程同上:先執行外部查詢,外部查詢返回的每一行,子查詢分別執行一次

select * from t_class c

返回:1 一班

select * from 學生表 s where s.c_id=1

有2行資料返回 → 證明存在 →不滿足 not exists→不顯示

(只需要返回其中一條即可證明→由exists的核心演算法決定)

2 二班

select * from 學生表 s where s.c_id=2

分析同上。

3 三班

select * from 學生表 s where s.c_id=3

無資料返回→證明 不存在→滿足not exists→顯示

思考:為什麼子查詢返回的資料不需要限制?

並不在乎返回的是什麼資料,而在乎有沒有資料返回

select * from 學生表 s where s.c_id=2

效果等價於

select 1,'x' from 學生表 s where s.c_id=2

查詢不存在時,有乙個簡單的方法:not in

select * from t_class c

where c_id not in (select distinct c_id from 學生表)

如果子查詢返回多行資料,必須用in,如果返回一行,才能用=,>,!=等

select * from t_class c

where c_id = (select distinct c_id from 學生表)

錯誤:子查詢返回的值多於乙個

邏輯:用=只能等於乙個值,現在有多個值,所以不能用=,應該用in

python練習 學生班級分配問題

題目要求 四個班級,八個學生,隨機將八個學生平均分配到四個班級中,也就是每乙個班級有且只有兩個學生。import random classes students a b,c d e f g h index random.randint 0,3 classes index 0 flag 0while ...

班級資訊的學生類

include include using namespace std class stu 宣告基類 void display protected 訪問許可權為保護型的資料成員 int num 學生學號 string name 學生姓名 class studetail public stu 宣告派生...

學生學號判斷專業班級

學生的學號為12位,其組成為 年份 2位 專業資訊 6位 班級 2位 班內序號 2位 例如學號 111909030208 11 代表2011年入學,190903 代表網路工程專業,02 代表在網路工程專業的02班,08 為班內序號。已知資訊工程系三個專業的 為 190901 電腦科學與技術專業 19...