这一节主要包含以下内容:
-
内连接
-
左外连接
-
右外连接
-
全连接
-
跨连接
-
子查询
一、内连接
说明:
提取两表中某列相同的数据,查询两个表提取表中内容。
语法:
SELECT table1.columns,table2.columns
FROM table1
INNER JOIN table2
ON table1.common_filed =table2.common_field;
示例:
select employees.name, employees.salary,department.dept
from employees
inner join department
on employees.id=department.id;
结果:
二、左外连接
说明:
左外连接返回从“ON”条件中指定的左侧表中的所有行,只返回满足条件的另一个表中的行。
语法:
SELECT table1.columns, table2.columns
FROM table1
LEFT OUTER JOIN table2
ON table1.common_filed = table2.common_field;
示例:
select employees.name, employees.salary,department.dept
from employees
left outer join department
on employees.id=department.id;
结果:
三、右外连接
说明:
右外连接返回从“ON”条件中指定的右侧表中的所有行,只返回满足条件的另一个表中的行。
语法:
SELECT table1.columns, table2.columns
FROM table1
RIGHT OUTER JOIN table2
ON table1.common_filed = table2.common_field;
示例:
select employees.name, employees.salary,department.dept
from employees
right outer join department
on employees.id=department.id;
结果:
四、全外连接
说明:
全外连接从左表和左表中返回所有行。 它将NULL置于不满足连接条件的位置。
语法:
SELECT table1.columns, table2.columns
FROM table1
FULL OUTER JOIN table2
ON table1.common_filed = table2.common_field;
示例:
select employees.name, employees.salary,department.dept
from employees
full outer join department
on employees.id=department.id;
结果:
五、交叉连接
说明:
将第一个表的每一行与第二个表的每一行相匹配。 它也被称为笛卡尔积。 如果table1具有“x”行,而table2具有“y”行,则所得到的表将具有(x * y)行。
语法:
SELECT coloums
FROM table1
CROSS JOIN table2;
示例:
select employees.name, employees.salary,department.dept
from employees
cross join department;
结果:
六、子查询
说明:
子查询或内部查询或嵌套查询是一个PostgreSQL查询中的查询,它可以嵌入到WHERE子句中。
必须遵循如下规则:
- 子查询必须括在括号中。
- 子查询在SELECT子句中只能有一列,除非主查询中有多个列用于比较其所选列的子查询。
- ORDER BY不能用于子查询,尽管主查询可以使用ORDER BY。 GROUP BY可用于执行与子查询中的ORDER BY相同的功能。
- 返回多行的子查询只能与多个值运算符一起使用,例如:IN,EXISTS,NOT IN,ANY / SOME,ALL运算符。
- BETWEEN运算符不能与子查询一起使用; 但是,BETWEEN可以在子查询中使用。
1.带SELECT语句的子查询
语法:
SELECT column_name [,column_name ]
FROM table1 [,table2 ]
WHERE column_name OPERATOR(
SELECT column_name [,column_name ]
FROMtable1 [,table2 ]
[WHERE]);
示例:
select * from employees
where id in (select id from employees where salary > 100000);
结果:
2.带INSERT语句的子查询
语法:
INSERT INTO table_name [(column1 [,column2 ])]
SELECT [* | column1 [,column2 ]
FROM table1 [,table2 ]
[WHERE VALUE OPERATOR ];
示例:
insert into employees1
select * from employees
where id in (select id from employees);
结果:
直接将employees表中的数据复制进了employees1里面。(employees1是employees的备份)
3.带UPDATE语句的子查询
语法:
UPDATE table
SET column_name =new_value
[WHERE OPERATOR [VALUE]
(SELECT COLUMN_NAME FROM TABLE_NAME)
[WHERE)];
示例:
update employees set salary=salary * 0.5
where age in (select age from employees1 where age > 22);
结果:
选择employees1里面age>22的数据,在employees中乘以0.5
4.带DELETE语句的子查询
语法:
DELETE FROM TABLE_NAME
[WHERE OPERATOR [VALUE]
(SELECT COLUMN_NAME FROM TABLE_NAME)
[WHERE)];
示例:
delete from employees
where age in (select age from employees1 where age=24);
结果: