【发布时间】:2010-11-21 18:27:58
【问题描述】:
如果你觉得这个问题对论坛来说很简单 - 把它归咎于我,我会道歉,因为我只是这个问题的新手。
我在 MS Access 中有这两个表:
通过 Comments.parent ID = Items.ID 连接的表 Items 和表 Comments。
我需要一个查询来显示 Items 表中的最后 10 条记录,每条记录包含
物品.id 项目.title 项目文本 项目,修改日期 项目的评论数 [如果有的话] 最后评论[如果有的话] 客人姓名 最后评论[如果有的话] date_modified
到目前为止,我得到了这样的东西:
选择前 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 commentscount 从项目 ,( SELECT t2.id as commentID, t2.guestName , t2.modified, t2.parentid FROM Comments as t2 ORDER BY t2.modified DESC ) as t3 在哪里 (Items.id = t2.parentid AND t3.commentID = (SELECT max(id) FROM Comments where parentid = Items.id)) ORDER BY Items.modified DESC 联盟 SELECT Items.id AS item_id, Items.* , null AS guestName, null AS comment_date, (SELECT count(*) FROM Comments where parentid = Items.id) as commentscount 从项目 WHERE (SELECT count(*) FROM Comments where parentid = Items.id) = 0 ) 作为 t4嗯。它正在工作,但我一直在问自己是否可以以更简单的方式完成。
欢迎提出任何建议。
提前谢谢你。
【问题讨论】:
-
Flinsch 和 Remou,非常感谢您的反应。我不得不做一些小的调整,但你发送的一般想法对我都很有用。这两个例子都让我朝着正确的方向前进,以提高我的 sql 知识,并且我的查询工作顺利。
标签: ms-access