char(n) 定長類型:無論夠不夠長度,實際都只佔據n個長度,不夠的話用空格補齊至n個長度,取出時將空格刪掉,利用率i/N
varchart(n) 變長類型:不用空格補齊,但在列內容前有1-2個字元來標誌該列的內容長度,利用率 i/i+(1-2)
n代表字元,不代表位元組
防止名字出現亂碼:set names gbk;
date存儲範圍1000-1-1----9999-12-31
創建表時,優先考慮常用和定長的信息,不常用信息和比較占空間的信息單獨建表
count() 返回的結果是總行數,不論是否滿足條件,因此count(socre)和count( score < 60 )得到結果是一樣的
對sum()和count()函數理解的不到位,想要計算至少有2門課掛了的人,使用count()函數,結果是 ?
sum()和score< 60 結合的理解:sum( score < 60) >=2 ==>計算出至少掛了2門課的人
select name,sum(score < 60) as gk ,avg(score) as pj from stu group by name having gk >=2;
where子查詢系列:
先查詢在排序」==>group by cat_id ,但goods_name, shop_price,我們應該取誰的呢?--解決思路:用到「子查詢」/連接查詢==>先排序再查詢
資料庫查詢?"投影式"查詢[要那列查那列,查的那列和其他列沒關係
select good_id, goods_name, shop_price from goods where goods_id in (select max(goods_id) from goods group by cat_id);
count(col)返回指定列中非null值的個數
將A、B表中id值相同的兩個num值相加
select id,sum(num) from (select * from ta union all select * from tb) as tmp
group by id;
更新和刪除操作要注意:where條件記得要加,除非對生活心灰意冷了否則還是加上比較好--不加影響的將是整個表的數據
select * from user where 1;--從user表中查找所有列,當條件恆真--【輸出所有】
例題:有如下表和數組
把num值處於[20,29]之間,改為20:update main set num=20 where num between 20 and 29; num值處於[30,39]之間的,改為30
update mian set num=( floor(num/10)*10 ) where num between 20 and 39;
把good表中商品名為諾基亞xxxx的商品,改為HTCxxxx,
提示:大膽的把列看成變數,參與運算,甚至調用函數來處理 .
substring(),--concat()
select goods_id, concat( LMS, substring(goods_name,4) ,shop_price from goods where goods_name like 諾基亞%;
對於數據表中,null不利於數據表優化操作,所以數據表中一般都對欄位設置not null
例題:select goods_id, goods_name,(market_price-shop_price) as min from goods where min > 200;
報錯:不識別min這個列!
【where子句針對的對象是磁碟上的數據表文件去select的,而select出來後的數據是存放在內存中的一個零時"結果集"】
例題:用exists型子查詢,查出所有商品的欄目下有商品的欄目
mysql> select * from category where exists (select * from goods where goods.cat_id = category.cat_id);
例題:Oracle的EMP表,查詢每個部門工資前三名的員工信息,如何寫?
select deptno, ename, sal from emp e1 where (select count(1) from emp e2 where e2.deptno=e1.deptno and e2.sal>=e1.sal) <=3 /*這裡的數值表示你想取前幾名*/ order by deptno, sal desc;
SQL執行順序:
MySQL不支持 full out join 轉而採用union
索引是什麼?
索引是一種排好序的快速查找數據結構
索引優化,單表分析
雙表:left join建在右表,right join建在左表
索引失效:
最佳左前綴法則:
Group by查詢優化:
全局查詢日誌(測試環境使用,永遠不要在生產環境使用):
鎖:
推薦閱讀: