數據庫之MySQL(MySQL學習筆記)——多表連接查詢、事物處理、索引

多表連接查詢

數據表的連接查詢比較常用的有內連接和外連接查詢兩種。

  • 內連接
    通過inner join … on 關鍵字實現的
 第一種:select * from commodity inner join commoditytype on c_type=ct_id;
第二種:select * from commoditytype inner join commodity on ct_id=c_type;

內連接第一種
內連接第二種
注意:兩種方式都能實現內連接,建議使用第二種:小表連接大表。查詢效率高。

  • 外連接
    外連接分爲兩種:左連接和有右連接
    左連查詢和右連查詢的區別是:以執行語句中的哪個表爲主表,所謂主表即以主表爲準,主表中有的數據才顯示,主表中沒有的數據即使附表中有也不顯示在結果中!
    左連接
select c_name,ct_name from commodity left join commoditytype on c_type=ct_id and ct_name='玩具';

左連接
右連接

select c_name,ct_name from commodity right join commoditytype on c_type=ct_id and ct_name='玩具';

右連接
內外、左右連接查詢的區別:
區別

  • 子查詢
    (1)單行單列

子連接:查詢name爲玩具的值

select c_name from commodity where c_type =(
select ct_id from commoditytype where ct_name='玩具');

子連接
(2)單行多列
這個基本不用到。

select * from table_a where (sal,name) = (
select sal,name from table_b where name = 'TomCat'
);//查詢結果在返回字段結果內的

(3)單列多行
查詢出文具或玩具商品

select c_name from commodity where c_type in (
select ct_id from commoditytype where ct_name='玩具' or ct_name='文具');

單行多列

select * from table_a where sal NOT IN (select sal from 
table_b;); //查詢結果不在返回字段結果內的
select * from table_a where sal >=ANY (select sal from 
table_b;); //查詢結果在返回字段結果內任意滿足(如果是數字的話只要大於等於最小的那個即可)
select * from table_a where sal >=ALL (select sal from 
table_b;); //查詢結果在返回字段結果內全部滿足(如果是數字的話必須大於等於最大的那個數字)

MySQL的數據處理

  • 數據的ACDI原則
    (1)原子性(atomic)
    (2)一致性(consist)
    (3)隔離性(isolated)
    (4)持久性(durable)
  • 事物的實現方法
set autocommit =0;//關閉MYSQL的自動提交
start transaction;//開始一個事物,標記事物的起始點
delete from `order`;//注意刪除表時,應先刪除子表;再刪除父表。
delete from customer;
commit|rollback;//提交一個事物給數據庫|將事物回滾,所有commit中的操作將被取消
set autocommit=1;//還原MySQL數據庫的自動提交

數據庫索引

記住兩點:
(1)提高查詢速度
(2)索引不是越多越好

  • 主鍵索引(primary key)
  • 唯一索引(unique)
  • 常規索引(index)
  • 全文索引(fulltext)
    問題:
    什麼時候需要添加索引?
    (1)在where,order by 子句中經常使用的字段。
    (2)字段的值是多個(例如性別字段則不適合)。
    (3)字段內容不是經常變化的,注意:經常變化的字段,添加索引反而降低性能。
    (4)不宜過多添加索引,注意:每添加一條索引都會佔用磁盤空間。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章