PostgreSQL JOIN,数组类型包含数组元素

时间:2014-10-29 18:39:34

标签: sql arrays postgresql join

我有两个表标签和用户

表名:标签

| id | name  |  
| 1  | one   |   
| 2  | two   |   
| 3  | three |   
| 4  | four  |   
| 5  | five  |   

表名:用户

| id | fname | tags      |  
| 1  | Ram   | {1,5}     |
| 2  | Sham  | {1,2,3,4} |
| 3  | Bham  | {1,3}     |
| 4  | Kam   | {5,2}     |
| 5  | Lam   | {4,2}     |

预期产出:

| id | fname | tags                  |
| 1  | Ram   | one, five             |
| 2  | Sham  | one, two, three, four |
| 3  | Bham  | one, three            |
| 4  | Kam   | five, two             |
| 5  | Lam   | four, two             |

试验-1:使用JOIN

SELECT I.id, I.fname, I.tags, J.name FROM users I 
JOIN tags J ON J.id = ANY(I.cached_tag_ids) 
LIMIT 1

结果:

| id | fname | tags |
| 1  | Ram   | one  |
| 1  | Ram   | five |

预期:

| id | fname | tags       |
| 1  | Ram   | one, five  |

1 个答案:

答案 0 :(得分:2)

您的tags应该有INTEGER[]类型。

CREATE TABLE users(
   id SERIAL,
   fname VARCHAR(50),
   tags INTEGER[]
);

然后,

SELECT I.id, I.fname, array_agg(J.name) 
FROM users I 
LEFT JOIN tags J 
ON J.id = ANY(I.tags) 
GROUP BY fname,I.id ORDER BY id

应该有效。见sqlfiddle

question可能有所帮助。