主要涉及:JOIN 、JOIN 更新、GROUP BY HAVING 數據查重/去重 ...
主要涉及:JOIN 、JOIN 更新、GROUP BY HAVING 數據查重/去重
1 INNER JOIN、LEFT JOIN、RIGHT JOIN、FULL JOIN(MySQL 不支持)、CROSS JOIN
這是在網上找到的非常好的一篇博文,圖解 join 語句:
下圖可以很清楚的明白,join 的數據選取範圍
[][1]
[1]: http://7xs09x.com1.z0.glb.clouddn.com/160725-imooc-mysql-development-skills-notes-001.png
2 更新使用過濾條件中包括本身的表
更新 t1 t2 表中 col_a 重覆的欄位
UPDATE t1
SET col_a = 'hi'
WHERE t1.col_a IN (
SELECT b.col_a
FROM t1 a INNER JOIN t2 b on
a.col_a = b.col_a
)
;
ERROR:1093
可轉換為:
UPDATE t1 aa JOIN(
SELECT b.col_a
FROM t1 a INNER JOIN t2 b on
a.col_a = b.col_a
)bb on aa.col_a= bb.col_a
SET col_a = 'hi'
;
3 查詢重覆數據、刪除重覆數據
利用 GROUP BY 和 HAVING 查詢重覆數據
SELECT col_a, COUNT(*)
FROM t1
GROUP BY col_a HAVING COUNT(*) > 1
;
刪除重覆數據,對於相同數據保留 ID 最大的
DELETE a
FROM t1 a JOIN (
SELECT col_a,COUNT(*),MAX(id) AS id
FROM t1
GROUP BY col_a HAVING COUNT(*) > 1
)b ON a.col_a = b.col_a
WHERE a.id < b.id
;