3

我正在尝试从 3 个表中生成一个“历史/日志页面”,表如下所示:

表A

CreationDate
ModifDate
LastAccessedDate
FileName

表B

Guid_TableA
CreationDate
ModifDate
LastAccessedDate
FileName

表C

Guid_TableA
LastModifDate
FileName

FWIW,尽管列名相似,但这些表中的日期之间没有关系。它们之间唯一相关的有效列是Guid_TableA

我想要的是...

选择记录并按日期排序。我正在尝试构建事件日志,因此返回这样的重复条目是有效的(只要结果按日期正确排序)

(TableA)  file-1.txt    '01/01/2012 00:00:00' (CreationDate)
(TableA)  file-1.txt    '01/01/2012 00:00:01' (ModifDate)
(TableB)  file-2.txt    '01/01/2012 00:00:02' (CreationDate)
(TableA)  file-1.txt    '01/01/2012 00:00:03' (LastAccessedDate)

希望我的意图很明确;我基本上想选择按日期排序的记录(即针对多个交叉表列排序,包括重复的条目

我的问题是:这可能吗?如果是这样,怎么做?

4

1 回答 1

3

您想使用UNION ALL运算符来合并多个选择的结果:

SELECT FileName, CreationDate AS Date FROM TableA
UNION ALL SELECT FileName, ModifDate FROM TableA
UNION ALL SELECT FileName, LastAccessDate FROM TableA
UNION ALL SELECT FileName, CreationDate FROM TableB
-- ...etc
ORDER BY Date;

如果您想要那些“TableA”和“CreationDate”注释,您也可以将它们添加为文字字符串:

SELECT 'TableA', FileName, CreationDate AS Date, 'CreationDate' FROM TableA
UNION ALL SELECT 'TableA', FileName, ModifDate, 'ModifDate' FROM TableA
UNION ALL SELECT 'TableA', FileName, LastAccessDate, 'LastAccessDate' FROM TableA
UNION ALL SELECT 'TableB', FileName, CreationDate, 'CreationDate' FROM TableB
-- ...etc
ORDER BY Date;

这给了我:

TableA|file-1.txt|01/01/2012 00:00:00|CreationDate
TableA|file-1.txt|01/01/2012 00:00:01|ModifDate
TableB|file-2.txt|01/01/2012 00:00:02|CreationDate
TableA|file-1.txt|01/01/2012 00:00:03|LastAccessDate
于 2012-11-08T00:02:00.617 回答