I am trying to get data from a view which returns users name and tags (comma separated numbers). Now I want to get a user if it has a certain tag.
My view returns this:
id | name | tags
----+--------+--------------------
1 | Albert | 1,2,3,4
2 | Isaac | 11,22,33,40,50
3 | Marie | 44,110,220,330,500
4 | Ray | 111,222,333
I want to get a user which contains tag = 4. When I try to query using LIKE operation, it returns multiple users.
select * from users
where tags LIKE '%4%';
Output:
id | name | tags
----+--------+--------------------
1 | Albert | 1,2,3,4
2 | Isaac | 11,22,33,40,50
3 | Marie | 44,110,220,330,500
Desired Output:
id | name | tags
----+--------+--------------------
1 | Albert | 1,2,3,4
How do I tackle this problem?
Online playground link: https://onecompiler.com/postgresql/3zc7pfngm
2
Answers
Try the below query :-
Well,
LIKE
works in any database, but in PostgreSQL the string_to_array is your solutionI assume that all your tags are integers. Adapt to
text
if not.