WHERE子句中的SQL IN运算符

时间:2010-10-29 07:31:34

标签: sql arrays postgresql

以下查询:

SELECT SUM (peak_power) FROM t_mpi_pv WHERE info_id IN ( 
 SELECT mp_info_id FROM t_mp WHERE mp_id IN (
  ARRAY[29800001,29800008,29800015,29800022,29800029]
 )
)

不起作用。我收到错误:

  

“运算符不存在:integer = integer []”。

但是

SELECT SUM (peak_power) FROM t_mpi_pv WHERE info_id IN ( 
 SELECT mp_info_id FROM t_mp WHERE mp_id = 29800001  
)

作品。

我做错了什么?

2 个答案:

答案 0 :(得分:5)

尝试:

SELECT SUM (peak_power) FROM t_mpi_pv WHERE info_id IN ( 
 SELECT mp_info_id FROM t_mp WHERE mp_id IN 
  (29800001,29800008,29800015,29800022,29800029)
 )
)

答案 1 :(得分:1)

或者,使用以下语法:

SELECT  SUM(peak_power)
FROM    t_mpi_pv
WHERE   info_id IN
        (
        SELECT  mp_info_id
        FROM    t_mp
        WHERE   mp_id = ANY(ARRAY[29800001,29800008,29800015,29800022,29800029])
        )

如果将数组作为单个绑定变量或函数的参数传递,则非常有用:

CREATE FUNCTION fn_peak_power (mpids INT[])
AS
$$
        SELECT  SUM(peak_power)
        FROM    t_mpi_pv
        WHERE   info_id IN
                (
                SELECT  mp_info_id
                FROM    t_mp
                WHERE   mp_id = ANY($1)
                );
$$
LANGUAGE 'sql';