mySQL數據庫數據查詢操作詳解


   

查詢數據:

簡單查詢:

1.查詢所有數據:

select * from 表名

   #select * from info 查詢所有列

2.查詢指定列:

select code,name from info

3.查詢指定行(條件查詢):

select * from info where nation='n001'

select * from info where code='p001' or/and nation='n001'

4.給列制定名稱

select code as '代號' name as '姓名' from info

5.模糊查詢

select * from car where name like '%/_奧迪%'  #'%'---表示在‘奧迪’前后可以出現n個字符,'_'表示在‘奧迪’前后可以出現1個字符  

6.排序查詢 

select * from car order by price #根據價格進行排序,默認升序(asc),后面加desc降序

select * from car order by price asc,oil desc #先根據價格升序排列,在次前提下出現價格相同的項再按油耗降序排列

7.去重查詢

select distinct brand from car

8.分頁查詢

select * from car limit 5,5 跳過前面5條取5條數據

9.統計查詢(聚合函數)

數據條數:select count(主鍵/*) from car

取最大值/最小值:select max/min(price) from car

取平均值:select avg(price) from car

10.分組查詢

select brand,count(*) from car group by brand 

select brand from car group by brand having count(*)>=3

11.范圍查詢

select * from car where price>=40 and price <=60

select * from car where price between 40 and 60

12.離散查詢

select* from car where price in/not in(10,20,30,40)

 

高級查詢:

1.聯合查詢

select code,name from info

union

select code,name from nation

2.連接查詢

形成笛卡爾積

select * from info,nation where info.nation=nation.code

為了查詢效率更高可以篩選出重復的數據:

select info.name,info.sex,nation.name,info.birthday from info,nation where info.nation=nation.code

 

select info.name,info.sex,nation.name,info.birthday from info join nation on info.nation=nation.code

3.子查詢

---子查詢的結果作為父查詢的條件使用

i.無關子查詢

---子查詢和父查詢沒有關系,子查詢單獨拿出來可以執行

a.查找民族為“漢族”的所有人員信息

select * from info where nation =(select code from nation where name='漢族')

b.查詢所有廠商是“一汽大眾”的車

select * from car where brand in(select brand_code from brand where prod_code in(select prod_code from productor where prod_code='一汽大眾'))

ii.相關子查詢

查詢油耗低於該系列平均油耗的汽車信息

select * from car where oil<(該系列平均油耗)

select avg(oil) from car where brand= 該系列

 

select * from car a where oil<(select avg(oil) from car b where b.brand=a.brand)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM