如何将具有实际值的IN子句转换为join子句?

时间:2019-03-26 12:35:59

标签: sql postgresql

我想转换一个由实际值组成的IN子句,而不是使用join子句的子查询。

select max(c1) from t1 where t1.id IN (
1,2,3,4......1000
)
and t1.c2 = something

如何将该查询转换为联接子句?

3 个答案:

答案 0 :(得分:3)

您可以使用内联VALUES来构建数据集,并使用别名来赋予该数据集以及名称和列名。

SELECT
    yourData.id, map.b
FROM
    yourData
INNER JOIN
(
  VALUES
    (1,2),
    (2,4),
    (3,8)
)
  map(a,b)
    ON map.a = yourData.a

答案 1 :(得分:2)

如果您的序列呈线性增长,请使用generate_series

select max(c1) from t1    
join generate_series(1, 1000) ids on t1.id = ids
where t1.c2 = something

答案 2 :(得分:0)

您可以尝试以下操作

 with cte as
    (
    select 1 as col union all
    select 2 union all
    select 3 union all
    select 4 union all
    ---------
    -------
    select 1000
    ) select max(t1.c1) from 
       cte join t1 on cte.col=t1.id where t1.c2=something
相关问题