1. 程式人生 > >mysql語句查詢基礎

mysql語句查詢基礎

備份資料庫:

(1)匯出整個資料庫
Mysqldump -u root -p 資料庫名 > 匯出的檔名(2)匯出

某個資料表
Mysqldump -u root -p 資料庫名 表名>匯出的檔名匯入外部資料庫


Source 外部資料庫檔案路徑

為了避免亂碼的出現:
1,html、php的meta中的charset資訊的編碼
2,html、php

等檔案儲存的編碼格式
3,mysql資料庫中client使用的編碼格式
4,mysql資料庫表

欄位編碼

(1)in()在某個範圍(集合)之間

//獲得 商品id 為 3, 5, 7 ,8 這幾個商品的名稱 價格
    select * from goods where id in('3','5','7','8');

(2)Between and 在兩個值之間的資料

//查詢價格在1000-1500之間的商品資訊
    select * from goods where price between 1000 and 1500;(3)Order

by排序  排序方法(升序ASC,降序DESC)

//將獲得的商品按照 價格 由高到低 排序
    select * from goods order by price (4)limit限定獲得資料的數量,


limit 偏移量,想要獲得的記錄數量//獲得價格最高的前十個商品
    select * from goods limit 10 order by price DESC;
//獲得第11個到第20個商品
    select * from goods limit 10,10;


合計函式:

Max():最大值

Min():最小值

Count():統計總的記錄數

Avg():平均數

Sum():求和
3)欄位別名
欄位名 as 別名:

 select cat_id, count(cat_id) as num from ecs_goods group by cat_id;

Where是對資料庫中的欄位進行判斷
Having對查詢結果中的欄位進行判斷

//計算商品的平均價格在1000元以上的商品的分類:
    select avg(price) from goods having avg(price)>1000;

(1)使用union將多個select的查詢結果結合起來//查詢cat_id為3或者為4的資料,

要求cat_id為3的按照價格的升序排序,cat_id為4的按照價格的降序排序
    select * from goods where cat_id=3 order by price union select  

* from goods where cat_id=4 order by price DESC;


(2)union查詢時,預設不顯示重複的資料,但是可以通過在union後增加all選項,

將重複的結果顯示出來
 



1,如果一個select查詢語句 包含了另一select查詢語句 就稱之為子查詢//查詢

GSM手機 下的商品有哪些?
    select * from ecs_goods where id =(select id from

ecs_cat_recommend where cat_name=GSM手機);

2,from 型子查詢   
句式:select .... from (select .....) as name where ......

//取得商品分類為3或5,商品名為 諾基亞開頭的資料
select goods_name from(select * from ecs_goods where goods_id in(3,5)

and goods_name like '諾基亞%') as '這是虛擬表名字';