如何找出同一行中的2个值是否在另一个表中

时间:2018-08-17 06:24:55

标签: sql amazon-redshift

我想确定同一行中的2个值是否存在于另一个表中。 如果两个值同时存在,则仅返回该行。 我可能可以进行2次加入,但是有没有一种有效的方法? 有下面的东西吗?

table_1
+---------+---------------+------+
| id      | other_id      | key  |
+---------+---------------+------+
| 1       | 2             | A    |
| 2       | 1             | B    |
| 1       | 3             | C    |
| 4       | 2             | D    |
+---------+---------------+------+
table_2
+---------+
| id      |
+---------+
| 2       |
| 3       |
| 4       |
+---------+
SELECT
  *
from
  table_1
where
  (id, other_id)  in  (
    SELECT
      id
    from
      table_2
  )

output_table
+---------+---------------+------+
| id      | other_id      | key  |
+---------+---------------+------+
| 4       | 2             | D    |
+---------+---------------+------+

3 个答案:

答案 0 :(得分:1)

您可以尝试

SELECT *
FROM table1 t1                           
WHERE exists  (select 1 from table2 t2 where  t1.id=t2.id)                  
       and exists (select 1 from table2 t3 where  t1.anotherid=t3.id) ;

答案 1 :(得分:0)

使用exists

SELECT
  *
from
  table_1 t1
where exists
(
    select id from table_2 t2
    where t1.id = t2.id or t1.other_id = t2.id;
)

答案 2 :(得分:0)

select * from table_1
where table_1.id in (select table_2.id from table_2)

尝试一下,希望对您有所帮助!