I’m trying to make this query MySQL compatible:
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
)
I’ve tried the following according to 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)
However I’ve ran into a new problem: I can’t access the stories
table from the deepest subquery: Unknown column 'stories.id' in 'where clause'
I was not able to find any solution to this problem, but likely there is one and I just don’t see it.
Edit:
I found a MySQL compatible query:
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
)
I think it is equal to the first query. Could somebody please verify this for me?