PostgreSQL-11-WITH語句

一、WITH語句原理:通用表表達式(Common Table Expressions)/CTEs,在大型查詢中的輔助語句ci

WITHit

   name_for_summary_data AS (io

     SELECT Statement)原理

   SELECT columnscli

   FROM name_for_summary_data數據

   WHERE conditions <=> (查詢

                      SELECT column移動

                      FROM name_for_summary_data)di

   [ORDER BY columns] co

 

CREATE TABLE w1(id int PRIMARY KEY, companyname text, city text, client int);

INSERT INTO w1 VALUES

       (1,'c1','shanghai',2000),(2,'c1','beijing',1500),(3,'c1','shenzhen',1000),

       (4,'c1','guangzhou',1000),(5,'c2','shanghai',1500),(6,'c2','beijing',3000),

       (7,'c2','shenzhen',1000),(8,'c3','shanghai',1000),(9,'c3','beijing',1000),

       (10,'c3','shenzhen',4000);

       建立表格

 

WITH t AS (SELECT companyname,city,client FROM w1 WHERE companyname = 'c1')

       SELECT SUM(client) FROM t;

       先篩選出companyname爲c1的臨時表t,再對t進行檢索(這裏t並不存在,\d w2不返回內容)

       等價於 → SELECT SUM(client) FROM w1 WHERE companyname = 'c1';

 

WITH t AS (SELECT companyname,client FROM w1 WHERE city = 'shanghai')

       SELECT SUM(client) FROM t;

       查詢出上海市中c1,c2,c3三個公司的總客戶數量

 

 

二、按條件移動數據

CREATE TAbLE w2(id int PRIMARY KEY, companyname text, city text, client int); 建立空表w2

WITH t AS (

       DELETE FROM w1 WHERE client < 2000   條件,注意這裏會修改w1

       RETURNING * )                        RETURNING子句:返回數據

       INSERT INTO w2(SELECT * FROM t);     將數據插入w2表格

       按照條件將w1的數據移動到w2中

       注意區別 → CREATE TABLE w2 AS SELECT * FROM w1 WHERE client < 2000; 這裏不會改變w1數據

相關文章
相關標籤/搜索