我正在vBulletin论坛上工作。我们的想法是创建一个网页,管理员可以在其中查询所有最新帖子,并且"阅读"他们被标记为"已检查"。
网页工作得非常好,但是,查询速度有点慢,因为我们每天都会收到新帖子,现在它会在过去24小时内删除所有帖子。
要解决此问题,我希望它只提取尚未检查过的帖子。
原始查询如下:
SELECT
thread.forumid, thread.firstpostid, thread.lastpost, thread.lastposter, thread.lastpostid, thread.replycount,
thread.threadid, thread.title, thread.open, thread.views, post.pagetext AS preview, post.userid AS lastpuserid, threadread.readtime AS readtime, threadread.userid AS userid
FROM thread AS thread
LEFT JOIN deletionlog AS deletionlog ON (thread.threadid = deletionlog.primaryid AND deletionlog.type = 'thread')
LEFT JOIN post AS post ON (post.postid = thread.lastpostid)
LEFT JOIN threadread AS threadread ON (threadread.threadid = thread.threadid AND threadread.userid = 90122)
WHERE open <> 10
AND thread.lastpost >= 1494100000
AND thread.forumid NOT IN(0013482730313233343537)
AND thread.visible = '1'
AND post.visible = 1
AND deletionlog.primaryid IS NULL
GROUP BY thread.threadid
ORDER BY thread.lastpost DESC
要仅获取未经检查的帖子,我需要计算
thread.lastpost-threadread.readtime > 0
我的第一个解决方案是添加
AND thread.lastpost-threadread.readtime > 0
到where子句。但是,这导致了
LEFT JOIN threadread AS threadread ON (threadread.threadid = thread.threadid AND threadread.userid = 90122)
仅选择threadread.userid = 90122
而非threadread.threadid = thread.threadid
所以我的想法是
SELECT ... thread.lastpost-threadread.readtime AS isread
然后AND isread > 0
。这返回了错误
未知列&#39; isread&#39;
我最有可能尝试做一些非常愚蠢的事情,或者只是不明白这个问题是如何运作的,但我对如何解决我的问题提出了疑问。所以现在我问你们:)
答案 0 :(得分:0)
如果要使用表别名,请缩短名称,以便查询更容易编写和阅读。
然后,您需要修复JOIN
。 WHERE
子句将一些外连接转换为内连接。然后,将条件移动到适当的ON
子句。
我认为这就是你想要的:
SELECT t.forumid, t.firstpostid, t.lastpost, t.lastposter, t.lastpostid, t.replycount,
t.threadid, t.title, t.open, t.views, p.pagetext AS preview, p.userid AS lastpuserid, tr.readtime AS readtime, tr.userid AS userid
FROM thread t JOIN
post p
ON p.postid = t.lastpostid LEFT JOIN
deletionlog dl
ON t.threadid = dl.primaryid AND dl.type = 'thread' LEFT JOIN
threadread tr
ON tr.threadid = t.threadid AND tr.userid = 90122 AND
t.lastpost > tr.readtime
WHERE open <> 10 AND
t.lastpost >= 1494100000 AND
t.forumid NOT IN (0013482730313233343537) AND
t.visible = 1 AND
p.visible = 1 AND
dl.primaryid IS NULL
GROUP BY t.threadid
ORDER BY t.lastpost DESC;
我不确定GROUP BY
应该做什么。在非聚合列上使用没有聚合函数的GROUP BY
通常是一个非常糟糕的主意。在这种情况下,t.threadid
可能是表的主键,因此该表中的其他列都可以。但是,如果通过连接到其他表生成重复项会怎么样?