SQL Server 中的两个表相交

Intersect 类似于 UNION 命令。 它对两条 SQL 语句进行操作。 UNION 和 INTERSECT 之间的区别在于 UNION 选择出现在第一个或者第二个语句中的那些值,而 INTERSECT 返回出现在两个语句中的那些值。

语法

(SQL Statement 1)
INTERSECT
(SQL Statement 2)

在SQL Server中相交两个表示例

创建第一个表

CREATE TABLE employee

(

      [id] int NULL,

      [name] char(20) NULL,

      [department] varchar(45) NULL

) ON [PRIMARY]

插入一些值

insert into employee

select 1,'grape','HR' union all

select 2,'ravi','Manager' union all

select 3,'raushan','Finance' union all

select 4,'aman','Sales'

select * from employee

创建第二个表

CREATE TABLE emp

(

      [id] int NULL,

      [name] char(20) NULL,

      [salary] int NULL

) ON [PRIMARY]

插入一些值

insert into emp values (1, 'bill',15000);
insert into emp values (2, 'james',15000);
insert into emp values (3, 'bob',12000);

select * from emp

相交两个表

SELECT name FROM emp

INTERSECT

SELECT name FROM employee as CommonName
日期:2020-06-02 22:18:01 来源:oir作者:oir