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  |

最佳答案 您的代码应具有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可能有所帮助.

点赞