MySQL查詢邏輯處理語句

mysql中的完整的查詢語句: php

select 字段列表 from 表名 [where條件] [group by 字段] [having] [order by 字段 asc|desc] [limit [開始位置],長度] where:條件查詢 group by:分組 having:篩選 order by:排序 limit:截取記錄mysql

1、where經常使用運算符 比較運算符:sql

> >= < <= = !=、<>//不等於 in(v1,v2,v3)//等於某個值 select * from text where id in(1,2,3); between v1 and v2 區間 select * from text where id between 1 and 2;函數

2、邏輯運算符:spa

and(邏輯與) 1 select * from text where id=1 and id=2; or(邏輯或) 1 select * from text where id=1 or id=2; not(邏輯非) 1 select * from text where not id=1;code

3、is判斷:排序

is null:查詢字段值爲null的記錄 1 select * from text where id is null; is not nul //查詢字段值不爲null 1 select * from text where id not null;ci

4、模糊查詢:rem

like 像 %:表示任意字符,包括空字符 1 select * from text where name like "李%"; _:表示任意一個字符,不包括空 1 select * from text where name like "李_";字符串

5、group by:

分組

一、通常狀況下,group by須要與統計函數(聚合函數)一塊兒使用有意義,聚合函數:相似於php中的系統函數概念

二、用 group by 字段 分組後,這個字段有集中類型,就獲得幾條記錄,每一個分組默認取第一條 mysql的五大統計函數:

一、max:求最大值 select max(shop_price) from goods; select max(shop_price) from goods group by cat_id;//求每一個分類中價格最高的手機

二、min:求最小值 select min(shop_price) from goods;

三、sum:求總和(as totalNum取個別名) select sum(shop_price) as totalNum from goods; select sum(shop_price) as typeTotalNum from goods group by cat_id;//求每一個分類的總和

四、avg:求平均值 select avg(shop_price) as avgPrice from goods; select avg(shop_price) as avgPrice from goods group by cat_id;//求每一個分類平均值

五、count:求總行數 select count(*) from goods;

select cat_id,count(*) from goods group by cat_id;//求每一個類型下的商品種類數量

//找出商品種類>=4的分類,主要類型ID(cat_id)以下2種

select cat_id,count(*) as t from goods group by cat_id having t >= 4;

select cat_id from goods group by cat_id having count(*) >= 4;

//查詢每一個分類下積壓的貨款

select cat_id,sum(goods_price*goods_num) as hk from goods group by cat_id;

6、mysql中的其餘函數

ceil()//向上取整

floor()//向下取整

round()//四捨五入

upper()//轉大寫

lower()//轉小寫

curdate()//當前日期

curtime()//當前時間

now()//當前日期時間

year("2015-09-21")//求年

month("2015-09-21")//求月

day("2015-09-21")//求天

hour("22:22:09")//求時

minute("22:22:09")//求分

second("22:22:09")//求秒

concat("str","str1")//拼接字符串或者字段

distinct//對記錄去重複,每一個字段相同 1 select disinct goods_name from goods;

案例: 建立商品表 編號 商品名稱 商品進貨價 商品售價 庫存 商品類型
 

create table goods( 
id int auto_increment primary key, 
goods_name varchar(30) not null default "", 
goods_price decimal(6,2) not null default "0.00",
shop_price decimal(6,2) not null default "0.00", 
goods_num smallint not null default 0,
cat_id tinyint not null default 0 ) 

insert into goods(goods_name,goods_price,goods_price,shop_price,goods_num,cat_id)
values 
("諾基亞",1500.00,1600.00,5,1),
("小米",2500.00,2600.00,6,1), 
("堅果",800.00,900.00,7,1),
("錘子",1500.00,2600.00,8,1),
("魅族",1500.00,1700.00,9,1), 
("蘋果4",3500.00,4600.00,15,3),
("蘋果5",4500.00,5600.00,15,3),
("蘋果6",5500.00,6600.00,15,3);
相關文章
相關標籤/搜索