MS Access sql查询论坛表

时间:2010-11-21 18:27:59

标签: ms-access

如果您觉得这个问题对于论坛来说很简单 - 请责怪我,我会道歉,因为我只不过是这个问题的新手。

我在MS Access中有两个表:

表项目和表由Comments.parent ID = Items.ID连接的注释。

我需要一个查询,它将显示Items表中的最后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

好。它正在发挥作用,但我一直在问自己,这是否可以通过更简单的方式完成。

任何建议都会受到欢迎。

提前谢谢。

2 个答案:

答案 0 :(得分:0)

SELECT TOP 10
Item.id,
Item.title,
Item.text,
Item.modified,
COUNT(Comment.id) AS count_of_comments,
(SELECT TOP 1 Comment.guest_name FROM Comment WHERE Comment.parentid = Item.id ORDER BY Comment.modified DESC) AS last_guest_name,
MAX(Comment.modified) AS last_comment_date
FROM Item
LEFT JOIN Comment ON Comment.parentid = Item.id
GROUP BY Item.id
ORDER BY Item.modified DESC

我不确定内部SELECT语句是否也可以更恰当地整合。也许我们也可以ORDER BY Comments.modified DESC然后“选择”guest_name拒绝嵌套的SELECT语句,但我不确定。

(我还没有测试过。)

答案 1 :(得分:0)

如何处理以下内容:

SELECT TOP 10
       Item.id,
       Item.title,
       Item.text,
       Item.date_modified,
       c.CommentCount,
       c.LastComment,
       c.LastGuestName,
       c.LastModDate
FROM Item
LEFT JOIN
(SELECT ParentID, 
       Count(ParentID) As CommentCount, 
       Last(Comment) As LastComment, 
       Last(guestName) As LastGuestName,
       Last(date_modified) As LastModDate
FROM Comments
GROUP BY ParentID
ORDER BY date_modified DESC) c
ON Item.ItemID=c.ParentID
ORDER BY item.date_modified