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字段实际上是超链接到其他qids。 并且qid最多没有uid = 3(userID 3)的投票条目 另外,它必须按时间顺序排序。
答案 0 :(得分: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值。