Python34-02_數據庫----數據庫條件查詢

數據庫條件查詢

1. 分頁查詢

1. limit 查詢

select * from students limit 5;數據庫

2. limit分頁查詢(頁面+ 顯示個數)

select * from students limit 0, 2;函數

(從小到大排列)select * from students order by age desc, limit 0, 2;it

2. 聚合函數

1. count()計算總數

select count(*) from students;table

2. 聚合函數, 默認跳過null值

select count(ifnull(height, 0)) from students where gender = 1;class

3. max, min,sum, avg 最大值, 最小值, 求和, 平均值

select max(age) from students;select

4. round() 四捨五入

select round(avg(age) ,2) from students;rollup

3. 分組查詢

1. group by(按類分組)

select gender from students group by gender;分頁

2. group by + group_concat()  (按類分組, 並查詢其餘屬性)

select gender, group_concat(name) from students group by gender;im

3. group by + 聚合函數

select gender, count(age) from students group by gender;統計

4. group by + having (having至關於where, 用於group by中)

select gender, group_concat(name) from students group by gender having gender in (1, 2);

5. group by + with rollup  (在最後的記錄後面新增一行, 計算總數和統計結果)

select gender, count(*) from students group by gender with rollup;

 

4. 鏈接查詢

1. 內鏈接

select * from students inner join classes;

select s.name, c.name fromstudents as s inner join classes as c on s.cls_id = c.id;

(不使用inner join表示內鏈接) select s.name, c.name from students s, classes c where s.cls_id = c.id;

2. 左鏈接

select * from students s left join classes c where s.cls_id = c.id;

3. 右鏈接

select * from students s right join classes c where s.cls_id = c.id;

4. 自鏈接

select a.id, a.title from areas a inner join areas c on a.id = c.id where c.title = '陝西省';

select r.id, r.title from areas r inner join area.a on r.id = a.id where a.title = '西安市';

5. 子查詢

(查出高於平均身高的信息)  select * from students where height > (select avg(height) from students);

5. 外鍵(爲字段添加約束)

alter table students add foreign key(cls_id) references classes(id);

相關文章
相關標籤/搜索