mysql的select語句總結與索引使用


單表查詢:

查詢指定記錄    select ....where

帶IN的關鍵字查詢  not in

帶between and的范圍查詢 

select column1,column2 from table1 where column between 3 and 14;

帶like的查詢  %匹配任意長度的字符

查詢以b開頭,並以y結尾的水果的名稱

select f_name from fruit where f_name like 'b%y';

下划線‘_’,一次只能匹配任意一個字符。

查詢空值:  is null / is not null

select * from where c_email is null;

帶and的多條件查詢

select f_id , f_price from fruits where s_id = '101' and f_price >= 5;

帶 or的多條件查詢,or和in操作法實現的效果是一樣的。但是in更簡潔

查詢結果不重復:

select distinct s_id from fruits;

排序:

order by id desc   (降序) 默認ASC(升序)

如果order by后面有多個字段,則先對第一個排序,如果第一個比較相等,在對后面的排序;

分組查詢:

group by column  having  <條件表達式>

這經常和聚合函數在一起使用   max()   min() count()    avg()    sum()

select s_id ,count(*) as total  from  fruits group by s_id;

以上查詢了id供應商提供的水果名稱;

select s_Id , group_concat(f_name)  as names from fruit group by s_id;

group_concat()將每個分組的名稱顯示

Having 過濾分組

select s_id , group_concat(f_name) as names from fruits group by s_id having count(f_name) > 1;

在group by 子句中使用with rollup

   添加一行,顯示字段的總和

也可多字段分組

select * from fruit group by s_id, f_name;

limit()限制查詢結果

連接查詢:

   內連接:  (inner join)

select suppliers.s_id , s_name , f_price from fruit , suppliers 

where fruits.s_id = suppliers.s_d;

內連接查詢語句:

select ...form fruits inner join suppliers on fruit.s_id = suppliers.s_id;

 

索引使用:

create index indexname on  tablename (column1, column2);

添加主鍵索引: alter table tablename  add  primary key (column)

添加唯一索引: alter table tablename add unique (column)

添加普通索引: alter table tablename add index index_name (column);

添加全文索引: alter table tablename add fulltext (clomn);

添加多列索引: alter table tablename add index index_name (column1 , column2...)

刪除索引 :drop index index_name on table_name;

查看索引使用情況: show status like "Handler_read%";

https://www.cnblogs.com/cxxjohnson/p/8625719.html

 


免責聲明!

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



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