標籤:表查詢總結
1 單表查詢
查詢所有欄位
select * from table_name
查詢指定記錄
and not like desc asc
order by
in 關鍵字 in (1,2,3,4)
between 關鍵字 between 1 and 2
like %或者_ 查詢模糊比對的
_ 代表1個
% 代表1個或者多個。
and 的多條件查詢 and 優先生效
or 的多條件查詢
district 不同
多列排序
select * from city where id<10 order by contry name
分組查詢 group by
分組之後過濾使用 having
where 是在分組之前選擇資料
having 是在分組之後過濾的語句
求和 rollup 分組後的執行
多欄位分組
類似於 多欄位排序。
限制查詢結果行數量
linit start, pagesize
2 使用集合函數查詢
count(*)函數 count 不統計空的數值
* 整張表,行最多的那個
col_name 代表統計對應列的非空資料
sum() 求和函數 會進行全表掃描。
avg() 統計平均數
max() 求最大值 全表掃描 reset query cache; 先清楚掉緩衝
min()最小值
Regex查詢
^ 開始
$ 結尾
. 任意單個字元 出現位置很重要。
* 匹配零個或多個
+ 匹配1次或多次
[abc] [^abc] 匹配中括弧中的任意一個
{start,end} 開始次數
例子:select uid from onethink_member where uid regexp ‘^1‘ ;
mysql> select uid from onethink_member where uid regexp ‘1$‘ ;
總計:盡量不用 select *
group by 和 order by 語句會大大增加執行查詢消耗
資料量大的時候,慎用集合函數
如果一條查詢語句經常被執行,where 裡面的語句最好有索引
3 子查詢
any some 子查詢 any 任何
表示滿足其中任一條件
例子:select uid from onethink_member where uid > any (select uid from onethink_ucenter_member );
exists 和 not exists 子查詢
子查詢資料存在在查詢,沒有在不查詢;
例子:select uid from onethink_member where uid = exists (select uid from onethink_ucenter_member );
mysql> select uid from onethink_member where uid != exists (select uid from onethink_ucenter_member );
in 子查詢
例子:
mysql> select uid from onethink_member where uid in (select id from onethink_ucenter_member where id > 900 );
union 子查詢
用於合并查詢結果 union all 就不去掉重複了。
列必須相同 all 關鍵字 把兩種表做拼接
create table table_name2 like table_name1;//複製表結構
mysql> select uid as id from onethink_member union select username as uname from onethink_ucenter_member;
mysql> select uid as id, nickname from onethink_member union all select username as uname,id from onethink_ucenter_member;
總結:
多表查詢注意名稱的唯一性
內連結比外連結效率高
注意笛卡爾積問題
查詢最好有索引
mysql 表查詢