如果你会发现这个问题对于论坛来说很简单 - 将责任归咎于我,我会道歉,因为我不过是这个问题的新手。论坛表的MS Access sql查询
我在MS访问这两个表:
表项和表评论由Comments.parent ID = Items.ID连接。
我需要将显示最近10条记录,从项目表的查询,包含
Item.id Item.title Item.text Item,date_modified count of Comments [if any] for the Item last Comments[if any] guestName last Comments[if any] date_modified
到目前为止,我有这样的事情每个记录:
SELECT TOP 10 t4.id, t4.* FROM ( SELECT Items.id AS item_id , Items.*, t3.guestName , t3.modified AS comment_date ,(SELECT count(*) FROM Comments where parentid = Items.id) as comentscount FROM Items ,(SELECT t2.id as commentID, t2.guestName , t2.modified, t2.parentid FROM Comments as t2 ORDER BY t2.modified DESC ) as t3 WHERE (Items.id = t2.parentid AND t3.commentID = (SELECT max(id) FROM Comments where parentid = Items.id)) ORDER BY Items.modified DESC UNION SELECT Items.id AS item_id, Items.* , null AS guestName, null AS comment_date, (SELECT count(*) FROM Comments where parentid = Items.id) as comentscount FROM Items WHERE (SELECT count(*) FROM Comments where parentid = Items.id) = 0 ) AS t4
嘛。它正在工作,但我一直在问自己,如果这可以以更简单的方式完成。
任何建议将更受欢迎。
预先感谢您。
Flinsch和Remou,非常感谢你对你的反应。我必须做一些小的调整,但你发送的一般想法对我来说都非常有用。这两个例子都让我朝着正确的方向前进,以提高自己的SQL知识,并使查询顺利进行。 – novice17 2010-11-22 11:38:57