我对一些奇怪的 sql 查询有疑问。我正在使用 MySQL,我会更改数据库结构,但我不能。所以我必须用查询来解决我的问题。
所以我有3张桌子。挑战、用户挑战和用户订阅。我需要离开那里 3 如下:
我需要一个包含 Challenges.private = 0 的所有挑战的列表,并且我必须排除当前用户 ID 下的 Users_challenges 中出现的所有挑战(users_challenges.iduser = 414)。然后我需要可以具有challenge.private = 1或0的挑战,但它们列在第三个表(users_subscribed.iduser = 414)中,而且在这里我必须从挑战表中排除所有读取的ID。最后,我需要统一所有结果并按时间和限制对它们进行排序。
我希望我是正确的,因为这很令人困惑,至少对我来说:D
我当前的查询需要 26 秒才能执行:
SELECT *
FROM challenges
WHERE challenges.private = 0
AND challenges.isquest = 1
AND challenges.title like '%%'
AND challenges.id NOT
IN (
SELECT users_challenges.idchallenge
FROM users_challenges
WHERE users_challenges.iduser = 414
AND users_challenges.idquest IS NULL
GROUP BY users_challenges.idchallenge
)
UNION
SELECT *
FROM challenges
WHERE challenges.isquest = 1
AND challenges.title like '%%'
AND challenges.iduser
IN (
SELECT users_subscriptions.idsubscribedto
FROM users_subscriptions
WHERE users_subscriptions.iduser = 414
UNION
SELECT 414 AS idsubscribedto
)
AND challenges.id NOT
IN (
SELECT users_challenges.idchallenge
FROM users_challenges
WHERE users_challenges.iduser
IN (
SELECT users_subscriptions.idsubscribedto
FROM users_subscriptions
WHERE users_subscriptions.iduser = 414
UNION
SELECT 414 AS idsubscribedto
)
AND users_challenges.idquest IS NULL
GROUP BY users_challenges.idchallenge
)
ORDER BY TIME DESC
LIMIT 0,30
那么有没有办法简化这个查询并更快地获得相同的结果?谢谢