考慮到您關於在聯接中跨多行強制執行條件的初始查詢,讓我們詳細說明可用的技術。
1A。利用 EXISTS:
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')
1B。使用子查詢:
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')
1C。利用 JOIN:
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'
2A。使用 COUNT 次:
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
2B。使用字串處理:
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
注意:此方法利用 MySQL 特定的擴展,與其他方法相比效率較低。
以上是在 SQL 中連接表格時如何跨多行強制執行條件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!