如何在PostgreSQL中使用其他表中的值进行选择?

时间:2016-06-09 08:08:36

标签: sql postgresql between

我有两个问题:

  1. 从table1中选择*,其中my_value介于value1和value2之间;
  2. 从table2中选择value1,value2;
  3. table2中的value1和value2的集合是唯一的。 如何在第一个查询的where语句中插入查询2的所有结果集?

    Resolved: Using exists key:
    select *
    from t1
    where exists
    (
        select *
        from t2
        where t1.my_value between t2.value1 and t2.value2
    );
    

2 个答案:

答案 0 :(得分:3)

如果您希望表1中存在的记录在表2中匹配,EXISTS似乎是直截了当的:

select *
from t1
where exists
(
  select *
  from t2
  where t1.my_value between t2.value1 and t2.value2
);

答案 1 :(得分:1)

你可以加入两个表:

SELECT t1.*
FROM   t1
JOIN   t2 ON t1.myvalue BETWEEN t2.value1 AND t2.value2