天天看點

msyql 複雜語句

一、複雜查詢

1、子查詢

       獨立子查詢,相關子查詢。

       select-column子查詢(獨立/相關,标量子查詢)

       from-table子查詢(獨立,表子查詢)

       where-key子查詢(獨立/相關,比較子查詢)

       where-value子查詢(獨立/相關,比較子查詢)

       where-() 子查詢(獨立/相關,行子查詢)

       where-exist 存在子查詢(獨立/相關)

2、關聯查詢

       inner-join、left-join、right-join、full-join

       多表查詢 = inner-join

3、過濾

       條件過濾 where

       後過濾器 having(必須是select中有的列,對查詢結果過濾)

4、分組/聚合查詢

       一級分組(group by a),多級分組(group by a, b)

       分組計數(select count(1) ... group by ...)

       分組去重計數(select count(distinct(b)) ... group by a)

5、分組 topk

       select-column 相關子查詢:掃描行,增加組内排行字段,後過濾,組内排行 < k+1

       where-key 相關子查詢:掃描行,組内排行 <= k

       where-value 相關子查詢:掃描行,值 >= 組内第topk對應值

       where-value 相關子查詢:掃描行,id = 組内top1的id or id = 組内top2的id ... or id = 組内topk的id

二、更新/插入

1、複制列插入

       insert into ... select ...

2、複制列建立表

       适合在複雜查詢時,建立中間表

       create table ... as select ...

3、插入時列重複

(1)重複時,不插入

       insert ignore into ...

(2)重複時,更新列

       用于實作 upsert 功能

       insert into ... on duplicate key update a = a, b = values(b)

(3)重複時,删除舊列,插入新列

       replace into ...

4、關聯更新

       update table a

       join b on a.id = b.id

       where ...

       set a.name = b.name, b.count = a.count;