我試圖讓這個查詢MySQL的兼容:INTERSECT更換MySQL的
SELECT stories.*,
(SELECT id FROM models WHERE model_user_id = stories.user_id AND user_id = ? LIMIT 1)
AS c_model_id
FROM stories
WHERE
c_model_id IS NOT NULL
AND
EXISTS (
SELECT tag_id FROM stories_tags WHERE story_id = stories.id
INTERSECT
SELECT tag_id FROM models_tags WHERE model_id = c_model_id
)
我下面根據this question嘗試。
SELECT
stories.*,
(SELECT id FROM models WHERE model_user_id = stories.user_id AND user_id = ? LIMIT 1)
AS c_model_id
FROM stories
WHERE
c_model_id IS NOT NULL
AND
EXISTS (SELECT t1.tag_id FROM (
SELECT tag_id FROM stories_tags WHERE story_id = stories.id -- Here
UNION ALL
SELECT tag_id FROM models_tags WHERE model_id = c_model_id
) AS t1 GROUP BY tag_id HAVING COUNT(*) >= 2)
但是我遇到了一個新問題:我無法訪問從最深的子查詢的stories
表:Unknown column 'stories.id' in 'where clause'
我無法找到任何解決這個問題,但可能有是一個,我只是沒有看到它。
編輯:
我發現一個MySQL兼容查詢:
SELECT stories.*
FROM stories
INNER JOIN models ON model_user_id = stories.user_id AND models.user_id = ?
WHERE EXISTS
(
SELECT stories_tags.tag_id
FROM stories_tags
LEFT JOIN models_tags
ON models_tags.tag_id = stories_tags.tag_id
WHERE models_tags.model_id = models.id AND story_id = stories.id
)
我認爲它等於第一個查詢。有人可以幫我驗證一下嗎?
在'WHERE'子句中和'WHERE'子句中的子查詢中使用'c_model_id',是否引用SELECT'子句中的子查詢?如果是,那麼這也不起作用。 – fancyPants
@fancyPants是的,他們打算提及相同的。其實我找到了一個替代查詢,可能你可以判斷它是否真的是替代品。 – idmean