SQL从两个表中获取公共行

时间:2015-07-21 13:58:16

标签: sql

我有两张桌子T1和T2。

任何人都可以帮助一个SQL查询,它将从这两个表中获取公共行吗? (假设T1和T2各有100列)

P.S:我猜每个栏目的INNER JOIN不是一个好主意。

由于

7 个答案:

答案 0 :(得分:2)

如果您使用的是SQL Server 2005,那么您可以使用Intersect Key word,它可以为您提供常用记录。

SELECT column1
FROM table1
INTERSECT
SELECT column1
FROM table2

如果你想在输出中输入table1中的column1和column2,它们在两个表中都有共同的column1。

SELECT column1, column2
FROM table1
WHERE column1 IN
(
SELECT column1
FROM table1
INTERSECT
SELECT column1
FROM table2
)

答案 1 :(得分:2)

SELECT NAME FROM Sample1
UNION 
SELECT NAME FROM Sample2;

EX: Table Sample1
ID NAME
-------
1   A
-------
2   B
-------

Table Sample 2
ID NAME
--------
1   C
--------
2   B 
------

Output
NAME
----
A
---
B
---
C
---

答案 2 :(得分:1)

使用INTERSECT

SELECT * FROM T1
INTERSECT
SELECT * FROM T2

答案 3 :(得分:0)

是的,INNER JOIN将起作用。

例如SELECT(column_1,column_2,... column_n)FROM T1 JOIN T2 ON(条件)WHERE(条件)

此查询将根据ON条件获取两个表中的公共记录(的交集)。

答案 4 :(得分:0)

通过使用INTERSECT

SELECT * FROM EmployeeSalary
INTERSECT
SELECT * FROM ManagerSalary

答案 5 :(得分:0)

选择 * FROM table_one 相交 选择 * FROM table_two

答案 6 :(得分:-1)

select
  t1.*
from
  t1, t2
where
 (
  (t1.col1 is null and t2.col1 is null) or (
  (t1.col1         =   t2.col1        )
 ) and
 (
  (t1.col2 is null and t2.col2 is null) or (
  (t1.col2         =   t2.col2        )
 ) and
 (
  (t1.col3 is null and t2.col3 is null) or (
  (t1.col3         =   t2.col3        )
 ) and
 ....
 (
  (t1.col100 is null and t2.col100 is null) or (
  (t1.col100         =   t2.col100        )
 )