2017-05-08 228 views
0

我正在研究vBulletin论坛。这个想法是创建一个网页,管理员可以查询所有最新帖子并“读取”它们,以便将它们标记为“已检查”。Mysql计算结果在where子句中?

该网页的工作原理非常好,但是,查询速度有点慢,因为我们每天都会收到新帖子的贴子,现在它正在拉取过去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。这返回的错误

未知列“isread”

我最有可能试图做一些事情非常愚蠢的或根本不明白这是如何entiry查询工作,但我出来关于如何解决我的问题的想法。所以现在我问你们:)

+1

一些示例数据会很好。我无法遵循你的问题。 –

+1

@TimBiegeleisen这是小提琴:http://sqlfiddle.com/#!9/7dd95 – icecub

回答

0

如果你打算使用表别名,那么缩短名称,以便查询更容易编写和阅读。然后,您需要修复JOIN s。 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可能是该表的主键,所以该表中的其他列很好。但是,如果有其他表的连接产生重复,该怎么办?

+0

什么是匿名downvote的原因? –

+0

这不是我。我仍然在小提琴上工作 – icecub

+0

我很确定你的问题是'WHERE'条件将外连接变成内连接,这就是为什么我建议把条件放在'ON'子句中。 –