SQL tag list and tag filtering

后端 未结 1 771
难免孤独
难免孤独 2021-01-03 06:09

I have a SQL database in which I store users and tags associated to users (many to many relationship). I have the classic schema with users table, tags

相关标签:
1条回答
  • 2021-01-03 06:44

    left join the tags table and include the id's being searched for in the join clause and check for counts in having.

    SELECT u.id,u.name,GROUP_CONCAT(ut.tagid) as tags
    FROM users u 
    LEFT JOIN usertag as ut ON u.id = ut.userid 
    LEFT JOIN tags t ON t.id=ut.tagid AND t.ID IN (10,20,30) --change this as needed
    GROUP BY u.id,u.name
    HAVING COUNT(ut.tagid) >= COUNT(t.id) AND COUNT(t.id) = 3 --change this number to the number of tags
    

    One more option is to use FIND_IN_SET if there are limited values. For example,

    SELECT * FROM (
    SELECT u.*, GROUP_CONCAT(ut.tagid) as tags 
    FROM users as u 
    LEFT JOIN usertag as ut ON u.id = ut.userid 
    GROUP BY u.id
    ) T
    WHERE FIND_IN_SET('10',tags) > 0 AND FIND_IN_SET('20',tags) > 0
    
    0 讨论(0)
提交回复
热议问题