子查询或内部查询或嵌套查询是另一个PostgreSQL查询中的查询,并嵌入在WHERE子句中。
子查询可与SELECT,INSERT,UPDATE和DELETE语句以及=,<,>,> =,<=,IN等运算符一起使用。
SELECT子查询
子查询最常与SELECT语句一起使用。基本语法如下-
SELECT column_name [, column_name ] FROM table1 [, table2 ] WHERE column_name OPERATOR (SELECT column_name [, column_name ] FROM table1 [, table2 ] [WHERE])
考虑具有以下记录的COMPANY 表-
id | name | age | address | salary ----+-------+-----+-----------+-------- 1 | Paul | 32 | California| 20000 2 | Learnfk | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000 (7 rows)
现在,让无涯教程使用SELECT语句检查以下子查询-
testdb=# SELECT * FROM COMPANY WHERE ID IN (SELECT ID FROM COMPANY WHERE SALARY > 45000) ;
这将产生以下输出-
id | name | age | address | salary ----+-------+-----+-------------+-------- 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 (2 rows)
INSERT子查询
子查询也可以与INSERT语句一起使用,INSERT语句使用从子查询返回的数据插入另一个表。
基本语法如下-
INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT [ *|column1 [, column2 ] ] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ]
考虑一个表COMPANY_BKP,其结构与COMPANY表相似,并且可以使用相同的CREATE TABLE创建该表,并将COMPANY_BKP作为表名。现在,要将完整的COMPANY表复制到COMPANY_BKP,以下是语法-
testdb=# INSERT INTO COMPANY_BKP SELECT * FROM COMPANY WHERE ID IN (SELECT ID FROM COMPANY) ;
UPDATE子查询
子查询可以与UPDATE语句结合使用。使用带有UPDATE语句的子查询时,可以更新表中的单列或多列。
基本语法如下-
UPDATE table SET column_name=new_value [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ]
假设有可用的COMPANY_BKP表,它是COMPANY表的备份。
以下示例为AGE大于或等于27的所有客户在COMPANY表中将SALARY更新0.50次-
testdb=# UPDATE COMPANY SET SALARY = SALARY * 0.50 WHERE AGE IN (SELECT AGE FROM COMPANY_BKP WHERE AGE >= 27 );
这将影响两行,最后COMPANY表将具有以下记录-
id | name | age | address | salary ----+-------+-----+-------------+-------- 2 | Learnfk | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000 1 | Paul | 32 | California | 10000 5 | David | 27 | Texas | 42500 (7 rows)
DELETE子查询
子查询可以与DELETE语句结合使用,就像上面提到的任何其他语句一样。
基本语法如下-
DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ]
假设无涯教程有COMPANY_BKP表可用,它是COMPANY表的备份。
以下示例从AGE大于或等于27的所有客户的COMPANY表中删除记录-
testdb=# DELETE FROM COMPANY WHERE AGE IN (SELECT AGE FROM COMPANY_BKP WHERE AGE > 27 );
这将影响两行,最后COMPANY表将具有以下记录-
id | name | age | address | salary ----+-------+-----+-------------+-------- 2 | Learnfk | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000 5 | David | 27 | Texas | 42500 (6 rows)
参考链接
https://www.learnfk.com/postgresql/postgresql-sub-queries.html
标签:PostgreSQL,name,SubQueries,COMPANY,无涯,查询,WHERE,AGE,SELECT From: https://blog.51cto.com/u_14033984/8969981