我有2个表,一个“文档”表和一个“内容”表。它们看起来像这样(简化):
document table:
docID
docTitle
content table:
contentID
docID
dateAdded
content
对于每次内容更改,都会在“内容”表中插入新记录。这样,所有变化都有完整的历史记录。我希望获得所有文档的列表,并加入最新内容。它应该返回docID,docTitle和相关内容记录以及最新的“dateAdded”值。我的大脑现在让我失望,我将如何创建这个联接?
答案 0 :(得分:27)
这可以通过子查询来完成:
SELECT d.docID, docTitle, c.dateAdded, c.content
FROM document d LEFT JOIN content c ON c.docID = d.docID
WHERE dateAdded IS NULL
OR dateAdded = (
SELECT MAX(dateAdded)
FROM content c2
WHERE c2.docID = d.docID
)
这称为"groupwise maximum"查询
编辑:使查询返回所有文档行,如果没有相关内容则返回NULL。
答案 1 :(得分:4)
使用:
SELECT t.docid,
t.docTitle,
mc.dateAdded,
mc.content
FROM DOCUMENT t
JOIN (SELECT c.docid,
c.content,
MAX(c.dateAdded)
FROM CONTENT c
GROUP BY c.docid, c.content) mc ON mc.docid = t.docid
AND mc.dateadded = t.dateadded
这应该比相关子查询更快。
当文档没有内容记录时的替代方法:
SELECT t.docid,
t.docTitle,
mc.dateAdded,
mc.content
FROM DOCUMENT t
LEFT JOIN (SELECT c.docid,
c.content,
MAX(c.dateAdded)
FROM CONTENT c
GROUP BY c.docid, c.content) mc ON mc.docid = t.docid
AND mc.dateadded = t.dateadded
答案 2 :(得分:0)
你能不能只做一个简单的连接,并按日期排序,只抓住第一条记录?
SELECT docTable.docId, docTable.docTitle from docTable
INNER JOIN content ON content.docID = docTable.contentID
WHERE docTable.docId = <some id>
ORDER BY content.dateAdded DESC
答案 3 :(得分:-1)
这是一个2查询解决方案:
首先查询:
select docID, max(dateadded) from [TblContent] group by docID
第二次查询:
select [TblDocument].* from [TblDocument]
inner join [TblDocument] on [TblDocument].[Docid]=[FirstQuery].[DocID]
答案 4 :(得分:-1)
试试这个:
select d.id, d.docTitle, MAX(c.dateAdd)
from document_table d
left join content_table c
on d.id = c.docId
group by d.id
这背后的想法是:假设文件表有记录A与内容(1,2,3,4)和B相关(5,6,7,8)
document content
A 1
2
3
4
B 5
6
7
8
带有max(dateadded)的内部联接会给你
document content max(dateadded)
A 1 1-1-2009...
A 2 1-1-2009...
A 3 1-1-2009...
A 4 1-1-2009...
B 5 2-1-2009...
B 6 2-1-2009...
B 7 2-1-2009...
B 8 2-1-2009...
按分组ID后,您将获得
document content max(dateadded)
A 1 1-1-2009...
B 5 2-1-2009...
注意:内容ID不必与max dateadded
的id匹配