如果你會發現這個問題對於論壇來說很簡單 - 將責任歸咎於我,我會道歉,因爲我不過是這個問題的新手。論壇表的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