14

I have two tables tags and users

Table Name: tags

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

Table Name: users

| 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}     |

Expected output:

| 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             |

Trial-1 : using 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

Result:

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

Expected:

| id | fname | tags       |
| 1  | Ram   | one, five  |
2
  • IN the first row dont you mean one,five
    – Mihai
    Commented Oct 29, 2014 at 18:41
  • yes sorry my mistake
    – Manoj H L
    Commented Oct 29, 2014 at 18:57

1 Answer 1

14

Your tags should have a INTEGER[] type.

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

Then,

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

should work. See sqlfiddle

This question may help.

3
  • I am using the same query to create the users table... SELECT I.id, I.fname, I.tags, J.name FROM users I JOIN tags J ON J.id = ANY(I.tags) LIMIT 1 The SELECT query you have given returns | id | fname | tags | | 1 | Ram | one | | 1 | Ram | two |
    – Manoj H L
    Commented Oct 29, 2014 at 18:53
  • @Umega added sqlfiddle Commented Oct 29, 2014 at 19:04
  • @Umega use a left join then Commented Oct 29, 2014 at 19:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.