我删除了上一个问题,以便更容易理解。 我正在使用此数据库架构开发论坛:
ID:INT->PRIMARY-KEY->AUTO_INCREMENT
IDTOPIC:INT (0 if it is the "father" topic OR father's ID if it's a reply)
IDUSER:INT (ID of user who posted)
CONTENT:MEDIUMTEXT
DATE:TIMESTAMP
我需要按日期排序查询,在哪里只获取最后一个帖子回复(如果“我是最后一个回复的用户”,IDUSER<> $ userid)或父线程主题,如果没有回复。 即使是主题或回复结果,我也需要打印第一个线程IDTOPIC / IDUSER
我理想的结果应该是这样的:
ID:IDTOPIC:IDUSER:CONTENT:DATE:IDLASTREPLY:IDLASTUSERREPLY:LASTCONTENTREPLY:LASTDATEREPLY
如果最后四个字段为NULL,则没有问题。 我需要尽可能快的查询。 请帮帮我!
答案 0 :(得分:1)
SELECT fa.ID, fa.IDTOPIC, fa.IDUSER, fa.CONTENT, fa.DATE,
re.ID as IDLASTREPLY,
re.IDUSER as IDLASTUSERREPLY,
re.CONTENT as LASTCONTENTREPLY,
re.DATE as LASTDATEREPLY,
CASE WHEN (re.DATE is NULL) THEN fa.DATE ELSE re.DATE END as LASTUPDATE
FROM post fa
LEFT JOIN post re ON re.ID =
(SELECT ID FROM post WHERE IDTOPIC = fa.ID ORDER BY DATE DESC LIMIT 1)
WHERE fa.IDTOPIC = 0
ORDER BY LASTUPDATE DESC
和ORDER如你所愿。
但这并不是那么好的表现。我认为你可以改善你的桌面结构。
编辑:为ORDER添加LASTUPDATE
答案 1 :(得分:0)
不幸的是,经过一些帖子后这个选择不太好...... 今天,桌面上总共有大约900条记录,当我用我的用户ID过滤线程时(只有45个不同的线程!),MySQL需要0.30秒(在开始时,只需要0.04 / 0.05秒...我认为恶化与我订阅的线程数成正比 这可能意味着当我将订阅300个不同的线程时,我应该等待大约2秒钟来进行此查询......这太过分了。 奇怪的是,如果我“限制0,10”这个查询或得到完整的查询,执行速度不会改变!这就是为什么我认为它不好......因为我认为即使我限制它也必须选择整个数据。 没办法解决。这就是我设置查询的方式。有一个新的通知表,因为我想将它用作通知查询(仅显示$ USERID所做的回复)
通知表字段:id,idcontent,userid
SELECT
CASE WHEN (re.id is NULL) THEN fa.id ELSE re.id END AS id,
fa.id as idtopic,
CASE WHEN (re.userid is NULL) THEN fa.userid ELSE re.userid END AS userid,
CASE WHEN (re.content is NULL) THEN fa.content ELSE re.content END AS content,
n.notify,
u.id as reuserid, u.name, u.surname, u.photo,
CASE WHEN (re.date is NULL) THEN unix_timestamp(fa.date) ELSE unix_timestamp(re.date) END AS LASTUPDATE
FROM notifications AS n
LEFT JOIN post AS fa
ON fa.id = n.idcontent
LEFT JOIN post AS re
ON re.id=(SELECT ID FROM post WHERE IDTOPIC = fa.ID AND userid <> $USERID ORDER BY DATE DESC LIMIT 1)
LEFT JOIN users AS u
ON u.id = ( CASE WHEN (re.userid is NULL) THEN fa.userid ELSE re.userid END )
WHERE
n.userid = $USERID
AND NOT (fa.userid = $USERID AND re.userid = $USERID)