SQL INTERSECT由一个字段获取另一个字段

时间:2017-11-14 18:41:27

标签: sql

我正在尝试执行此SQL查询:

 SELECT field FROM table
 INTERSECT
 SELECT field FROM table

哪个返回给定字段的交集,但是我想从表中获取另一个字段(与给定字段相交),我该怎么做?

4 个答案:

答案 0 :(得分:0)

我会使用EXISTS子查询:

SELECT t1.OtherField
FROM Table1 t1
WHERE EXISTS (
        SELECT 1
        FROM Table2 t2
        WHERE t2.Field = t1.Field
    )

或者,您可以使用IN子查询,这可能在某些RDBMS或配置中更好用:

SELECT t1.OtherField
FROM Table1 t1
WHERE t1.Field IN (
        SELECT t2.Field
        FROM Table2 t2
    )

答案 1 :(得分:0)

您可以使用IN

SELECT c1
FROM a
WHERE c2 IN (
        SELECT x1
        FROM b
        );

示例:

表:a

c1  c2
------
1   10
2   20
3   30

表:b

x1
---
20
30

<强>结果:

c1
--
2
3

DEMO

答案 2 :(得分:0)

这样的事情应该这样做:

查看joins

select 
    t1.AnyField, t2.AnyField
from 
    t1
    inner join t2 on t1.intersection_field = t2.intersection_field

根据你对同一张桌子的评论

select 
    t1.AnyField, t2.AnyField
from 
    table as t1
    inner join table as t2 on t1.intersection_field = t2.intersection_field
      and t1.another_field = t2.another_field

select 
    t1.AnyField, t2.AnyField
from 
    table as t1
    inner join table as t2 on t1.intersection_field = t2.intersection_field
where
    t1.filtered_field = 'text'
    and t2.yet_another_field >= 10

答案 3 :(得分:0)

SELECT anotherField 
FROM table b
JOIN table1 a ON a.field=b.field