day04【MySQL多表&事物】

主要內容

  • 多表查詢
  • 事物
  • DCL

1 多表查詢

  • 查詢語法
    select
    列名列表
    from
    表名列表
    where…
  • 笛卡爾積
    • 有兩個集合A,B.取這兩個幾個所有組成情況
    • 要完成多表查詢,需要消除無用的數據
  • 多表查詢的分類
  1. 內連接查詢:
    1. 隱式內連接:使用where條件消除無用數據
      select * from emp,dept where emp.dept_id = dept.id;
    2. 顯式內連接:
      語法:select 字段列表 from 表名1 [inner] join 表名2 on 條件
      例如:
      select * from emp inner join dept on emp.dept_id = dept.id;
    3. 內連接查詢:
      1. 從哪些表查詢數據
      2. 條件是什麼
      3. 查詢哪些字段
  2. 外連接查詢:
    1. 左外連接:查詢的是左表所有數據以及交集部分
    select 字段列表 from 表1 left [outer] join 表2 on 條件;
    select t1.*,t2.name from emp t1 left join dept t2 on t1.dept_id = t2.id;
    2. 右外連接:查詢的是右表所有數據及其交集部分
    select 字段列表 from 表1 right [outer] join 表2 on 條件;
    select * from dept t2 right join emp t1 on t1.dept_id = t2.id;
    1. 子查詢:查詢中嵌套查詢,稱嵌套查詢爲子查詢
      select * from emp where emp.salary = (select max(salary) from emp);
      1. 子查詢的結果是單行單列的:
        子查詢可以作爲條件,使用運算符:> >= < <= =
        查詢員工工資小於平均工資的人
        select * from emp where emp.salary < (select avg(salary) from emp);
      2. 子查詢的結果是多行單列的:
        子查詢可以作爲條件,使用運算符:in
        select * from emp where dept_id in(select id from dept where name in (‘財務部’,‘市場部’));
      3. 子查詢的結果是多行多列
        子查詢可以作爲一張虛擬表參與查詢
        select * from dept t1,(select * from emp where emp.join_date > ‘2011-11-11’) t2 where t1.id = t2.dept_id;
        普通內連接方法:
        select * from emp t1,dept t2 where t1.dept_id = t2.id and t1.join_date > ‘2011-11-11’;

2 事物

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章