问题:
确定同时拥有“tag1”的用户和 'tag2' 标签,同时避免使用 'IN' 的影响,这会返回带有以下任一内容的用户
解决方案:
要根据表 B 中的两个行条件从表 A 中选择行,请选择以下策略之一:
1。测试不同的行:
SELECT * FROM users WHERE EXISTS (SELECT * FROM tags WHERE user_id = users.id AND name ='tag1') AND EXISTS (SELECT * FROM tags WHERE user_id = users.id AND name ='tag2')
SELECT * FROM users WHERE id IN (SELECT user_id FROM tags WHERE name ='tag1') AND id IN (SELECT user_id FROM tags WHERE name ='tag2')
SELECT u.* FROM users u INNER JOIN tags t1 ON u.id = t1.user_id INNER JOIN tags t2 ON u.id = t2.user_id WHERE t1.name = 'tag1' AND t2.name = 'tag2'
2.聚合行:
SELECT users.id, users.user_name FROM users INNER JOIN tags ON users.id = tags.user_id WHERE tags.name IN ('tag1', 'tag2') GROUP BY users.id, users.user_name HAVING COUNT(*) = 2
SELECT user.id, users.user_name, GROUP_CONCAT(tags.name) as all_tags FROM users INNER JOIN tags ON users.id = tags.user_id GROUP BY users.id, users.user_name HAVING FIND_IN_SET('tag1', all_tags) > 0 AND FIND_IN_SET('tag2', all_tags) > 0
建议:
为了获得最佳可扩展性,如果可以出现多个标签,请考虑使用带有受保护标签或内部聚合的 COUNT对于用户。
以上是如何使用SQL连接高效查找具有多个标签的用户?的详细内容。更多信息请关注PHP中文网其他相关文章!