我要选择用户尚未拥有的所有图像。
我有三个表:user,image,和user_image:
user
image
user_image
LEFT JOIN/IS NULL
SELECT DISTINCT i.data FROM IMAGE i JOIN USER_IMAGE ui ON ui.image_id = i.id LEFT JOIN USER u ON u.id = ui.user_id AND u.user = ? WHERE u.id IS NULL
NOT IN
SELECT DISTINCT i.data FROM IMAGE i JOIN USER_IMAGE ui ON ui.image_id = i.id WHERE ui.user_id NOT IN (SELECT u.id FROM USER u WHERE u.user = ?)
NOT EXISTS
SELECT DISTINCT i.data FROM IMAGE i JOIN USER_IMAGE ui ON ui.image_id = i.id WHERE NOT EXISTS(SELECT NULL FROM USER u WHERE u.id = ui.user_id AND u.user = ?)
的LEFT JOIN/IS NULL和NOT IN提供相当的性能-的NOT EXISTS是〜30%的效率低。 有关更多详细信息,请参见此内容。