2016-07-24 110 views
3

我只是想知道如何在PostreSQL存儲過程中將整數列表存儲爲變量。如何在PostgreSQL中將整數列表存儲爲變量

例如,我有這樣的語句:

select A from B where C IN (1,2,3); 
    select A from B where C IN (1,2); 

我要聲明一個變量來存儲(1,2,3)(1,2)

所以我最終會像聲明:

select A from B where C in numberList; 

(numberList的值爲(1,2,3))我不知道我應該使用哪個數據類型

,我在線查詢並且無法找到psql中的列表類型。那麼這個語法是什麼?

回答

0

PostgresSQL Arrays

postgres的具有用於在表陣列有很大的數據類型。你有沒有試過?

+0

顯然不工作,我試過不已,其中C在numberList,它有語法錯誤,顯然不能像陣列中那樣做。 –

+0

@JamesXia:你需要使用'any'運算符:'where c = any(array_variable)',但只能在PL/pgSQL或SQL _functions_中工作,而不是普通的SQL(因爲SQL沒有變量) –

0

你可以在SQL中做到這一點。隨着如下定義的表:

test=> \d in_clauses 
    Table "laurenz.in_clauses" 
Column | Type | Modifiers 
--------+-----------+----------- 
id  | integer | not null 
list | integer[] | 
Indexes: 
    "in_clauses_pkey" PRIMARY KEY, btree (id) 

test=> SELECT * FROM in_clauses; 
id | list 
----+--------- 
    1 | {1,2,3} 
    2 | 
(2 rows) 

test=> \d searched 
    Table "laurenz.searched" 
Column | Type | Modifiers 
--------+---------+----------- 
id  | integer | not null 
val | integer | not null 
Indexes: 
    "searched_pkey" PRIMARY KEY, btree (id) 

test=> SELECT * FROM searched; 
id | val 
----+----- 
    1 | 3 
    2 | 3 
    3 | 4 
    4 | 1 
    5 | 5 
(5 rows) 

您可以(使用 「= ANY」 而不是在 「IN」)寫:

test=> SELECT searched.id 
     FROM searched 
      JOIN in_clauses ON (in_clauses.id = 1) 
     WHERE val = ANY (list); 
id 
---- 
    1 
    2 
    4 
(3 rows) 
相關問題