2
SELECT * FROM (
                SELECT qid,via,date,uid, via as cool FROM questions WHERE via != '' AND (uid = 3 OR `uid` IN (SELECT uid_followed FROM followers WHERE uid_follower =  3 AND unfollowed = 0))
                AND via NOT IN (SELECT qid FROM votes WHERE uid =  3)
                UNION ALL
                SELECT qid,via,date,uid, qid as cool FROM questions WHERE via = '' AND (uid = 3 OR `uid` IN (SELECT uid_followed FROM followers WHERE uid_follower =  3 AND unfollowed = 0))
                AND qid NOT IN (SELECT qid FROM votes WHERE uid =  3)
                ) as a
                GROUP BY cool
                ORDER BY date DESC

这需要 3 秒多的时间,并且我已在 qid 列和正确列中的 via 上放置了索引。复杂之处在于我想要一个唯一的 qid,并且某些行具有 qid,但实际上是通过 via 字段与其他 qid 的超链接。并且 qid 在投票中最多没有 uid = 3 (userID 3) 的条目,而且它必须按时间顺序排序。

4

1 回答 1

2

试试这个:

SELECT qid,via,date,uid,
case
    when via = '' then qid
    else via
end as cool
FROM questions
WHERE (via != ''
AND via NOT IN (SELECT qid FROM votes WHERE uid =  3)
OR via = ''
AND qid NOT IN (SELECT qid FROM votes WHERE uid =  3))
AND (uid = 3 OR `uid` IN (SELECT uid_followed FROM followers WHERE uid_follower =  3 AND unfollowed = 0))
ORDER BY date DESC

没有 UNION ALL 和 GROUP BY

告诉我是否还好。我使用 OR 逻辑运算符将两个查询合二为一。

您不关心 via 字段的 NULL 值。我使用你的符号(!=''或='')但也许你会考虑NULL值。

于 2013-09-09T13:17:57.687 回答