I have a table called users
another table called user_flags
, and another table called flags
The users
table contains a name
and id
The flags
table contains a name
and id
The user_flags
contains a user_id
and flag_id
If I want to get all the users which have any of the provided flag names, what would be the query? That is, if the query provides 'red' and 'blue' but a user is just associated with blue, we would return that User.
That is, if I have the following schema: http://sqlfiddle.com/#!9/ac105 - And the flag names that I passed were red
and blue
, it would return the row for the User John, because John has a red
associated flag.
Try this query:
SELECT u.name
FROM users u INNER JOIN user_flags uf
ON u.id = uf.user_id
INNER JOIN flags f
ON uf.flag_id = f.id
WHERE F.name = 'red'
Note that in the fiddle the table and column names are slightly different from what you used in your original question.
You need to join the tables on their id values and use a where clause for the flag color name. Something like this:
select * from Users U
join UsersFlags UF on UF.user_id = U.id
join Flags F on F.id = UF.flag_id
where F.name = 'red'
Try this one
SELECT s.id,s.name
FROM @users s
JOIN @users_flag uf ON s.id = uf.uid
JOIN @flag f ON f.id = uf.fid
WHERE f.NAME IN ('red','Blue')
SELECT u.id
,u.name
,f.name flag
FROM USERS u
JOIN flags f using(id)
JOIN UsersFlags uf on f.id=uf.flag_id
WHERE
f.name in ('red','blue') -- or f.name in (select name from flags)
-- or f.name = any(array['red','blue'])
and another one
SELECT u.NAME
FROM USERS u
WHERE id IN (
SELECT uf.user_id
FROM UsersFlags uf
JOIN flags f ON uf.flag_id = f.id
WHERE f.NAME IN (
'red'
,'blue'
)
)
output:
id name flag
-- ---- ----
1 John red
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.