1

我有五个结构非常相似的表,但差异很大,我想将它们作为单独的表。本质上,这些表将事件记录在五个不同的“类别”中,这些“类别”具有一些公共字段和一些其他独特的字段。

现在看来我需要编写一个报告,其中所有五个表中的记录按记录创建时间戳的降序显示(所有表的标准)。所有表都有我需要的公共字段,例如 fName、lName、scorePercent、numCorrect 等。

我似乎无法找到编写查询以从所有五个表中选择记录并将它们显示在一个表中的最佳方法,其中一列显示记录来自的表和公共字段的值,按降序排列约会时间。

有什么简单的方法可以做到这一点?我必须用 PHP 做吗?我开始质疑我原来的设计。

谢谢。

4

2 回答 2

2

如果数据足够相似,可以一起查询,那么它可能足够相似,可以一起存储一个表中,并带有一个额外的列来记录类型,但是......

select * from (
    select 'table1', timestamp_col, fName, lName, scorePercent, numCorrect
    from table1 where ...
    UNION ALL
    select 'table2', timestamp_col, fName, lName, scorePercent, numCorrect
    from table2 where ...
    UNION ALL
    select 'table3', timestamp_col, fName, lName, scorePercent, numCorrect
    from table3 where ...
    UNION ALL
    select 'table4', timestamp_col, fName, lName, scorePercent, numCorrect
    from table4 where ...
    UNION ALL
    select 'table5', timestamp_col, fName, lName, scorePercent, numCorrect
    from table5 where ..
) x
order by timestamp_col desc

您可以在内部查询之外使用单个 where 语句,但它的性能会很差,因为所有表的所有行都将合并。这样,只有实际需要的行被联合起来。

请注意,这UNION ALL是一个比 , 更好的选择UNION,因为UNION ALL不排序(UNION数据将被排序两次- 一次用于删除重复项,再次用于排序)。

于 2012-04-06T14:20:55.333 回答
0

您可以使用UNION ALL语句。所以也许是这样的:

SELECT
  fName, lName, scorePercent, numCorrect,date, 1 AS type
FROM
  table1
UNION ALL
SELECT
  fName, lName, scorePercent, numCorrect,date, 2 AS type
FROM
  table2
UNION ALL
SELECT
  fName, lName, scorePercent, numCorrect,date, 3 AS type
FROM
  table3
UNION ALL
SELECT
  fName, lName, scorePercent, numCorrect,date, 4 AS type
FROM
  table4
UNION ALL
SELECT
  fName, lName, scorePercent, numCorrect,date, 5 AS type
FROM
  table5
ORDER BY date
于 2012-04-06T14:17:25.407 回答