简单讲,CTE就是日常SQL中出现的with语句,其原理就是通过提前将数据查询出来后作为临时结果集使用,可以与SELECT \ INSERT \ UPDATE \ DELETE的SQL连用。
INSERT - 插入
WITH r AS (
SELECT code, name
FROM t1
)
INSERT INTO t2(code,name)
SELECT code,name
FROM r;
UPDATE - 更新
WITH r AS (
SELECT code, name
FROM t1
)
UPDATE t2
SET t2.name = t1.name
FROM t1
WHERE t1.code = t2.code;
SELECT - 查询
WITH r AS (
SELECT code, name
FROM t1
)
SELECT t2.*
FROM t2
WHERE EXISTS (SELECT 1 FROM t1 where t1.code = t2.code);
DELETE - 删除
WITH r AS (
SELECT code, name
FROM t1
)
DELETE FROM t2
WHERE code IN (SELECT code FROM t1);
RECURSIVE - 递归查询
WITH RECURSIVE r AS (
SELECT id, name, parent_id, 1 as level
FROM organization
WHERE parent_id IS NULL
UNION ALL
SELECT o.id, o.name, o.parent_id, oh.level + 1
FROM organization o
JOIN r oh ON o.parent_id = oh.id
)
SELECT id, name, level
FROM r;
WITH在一定程度能 解决数据库查询上的一些问题,但并不是每次适合,需要对照上述的优缺点,自行判断是否需要使用。
如果对你有所帮助,可以点赞、关注、收藏起来,不然下次就找不到了
【点赞】⭐️⭐️⭐️⭐️⭐️
【关注】⭐️⭐️⭐️⭐️⭐️
【收藏】⭐️⭐️⭐️⭐️⭐️
Thanks for watching.
–Kenny