一种“简单”的方法(只是修改您现有的查询)可能是将您的两个INNER JOIN
s 都变成LEFT JOIN
s 并at least one of the two joined successfully
在WHERE
子句中检查...
SELECT
*
FROM
products
LEFT JOIN
favorites
ON products.id = favorites.favorable_id
AND favorites.favorable_type = 'Product'
AND favorites.user_id = ?
LEFT JOIN
followings
ON products.merchant_id = followings.followable_id
AND followings.followable_type = 'Merchant'
AND followings.user_id = ?
WHERE
favorites.user_id IS NOT NULL
OR followings.user_id IS NOT NULL
这样做的缺点是表中的每条记录product
都必须由WHERE
子句检查。
如果该表很小,或者您通常以任何方式返回表的“大”部分,这可能没问题。但是,如果您只返回表的“一小部分”,您可能需要优化它,例如使用两个带有 的查询UNION
,正如您的问题标题所暗示的那样......
SELECT
products.*
FROM
products
INNER JOIN
favorites
ON products.id = favorites.favorable_id
AND favorites.favorable_type = 'Product'
AND favorites.user_id = ?
UNION
SELECT
products.*
FROM
products
INNER JOIN
followings
ON products.merchant_id = followings.followable_id
AND followings.followable_type = 'Merchant'
AND followings.user_id = ?
由于可能能够在和上使用索引,因此此处的每个查询都INNER JOIN
可能比整个基于查询的查询快得多。LEFT JOIN
followings(user_id, followable_type)
favorites(user_id, favorable_type)