mysql查詢語句的總結

1、基本構成

(1)需要查詢的表(單表,多表)

(2)需要查詢的信息(字段信息,過濾處理)

(3)查詢條件(字段關聯,字段值范圍,記錄截取設置,排序方式,分組方式,去重,or ,and)?

2、實例展示(以user表為例)

2.1查詢單表(user)

(1)查詢單表所有字段

select * from user;(select后面跟字段名,from后面跟表名,*代表所有字段, where后面跟條件)

(2)查詢單表特定字段

select user_id,user_name from user;(字段名之間用“,”隔開)

(3)查詢單表記錄總數count(),sum(),max(),min()用法相同,后面三個函數參數不能為*。

select count(*) from user;

(4)查詢單表,按user_id分組統計每組記錄總數,并按照user_id倒序

select count(*) from user group by user_id desc;

注意:分組字段只有一個時,可直接在后面加desc進行倒序,默認是正序,也可加上asc

(5)查詢單表,按user_id,user_name分組統計每組記錄總數,并按照user_id倒序

select count(*) from user group by user_id,user_name order by user_id desc;

注意:group by與order by同時使用,排序的字段user_id要出現在分組字段(user_id,user_name)中

?(6)查詢單表,條件為某個字段值范圍

user_id>=1并且=1 and user_id

user_id在1和2之間 ?:select * from user where user_id between 1 and 2;

user_id包含于(1,2):select * from user where user_id in(1,2);

user_id是1或2 ?:select * from user where user_id=1 or user_id=2;

(7)查詢單表,截取數據limit index,length

截取第1條:select * from user limit 1;或者select * from user limit 0,1;

截取第2條:select * from user limit 1,1;

(8)查詢單表,去重distinct?

select distinct user_name from user;

(9)having關鍵字,可以與合計函數一起使用;

select count(*) from user group by user_id desc?having max(user_weight)

2.2查詢多表(user,order)

(1)inner join(只返回匹配值)

select * from user inner join order on user.user_id=order.user_id;

(2)left join(返回匹配值和左表剩余值)

select * from user u left join order o on u.user_id=o.user_id;

注意:u和o是別名,方面使用

(3)right join(返回匹配值和右表剩余值)

select * from user right join order on user.user_id=order.user_id;

(4)full join(返回所有值)

select * from user full join order on user.user_id=order.user_id;

?

? 版權聲明
THE END
喜歡就支持一下吧
點贊15 分享