查看包含相同列的多个表
我有四个包含完全相同的列的表,并且想要创建所有四个表的视图,以便我可以一起查询它们。
这可能吗?
(由于繁琐的原因,我不能/不允许将它们组合起来,这将使这变得无关紧要!)
I have four tables containing exactly the same columns, and want to create a view over all four so I can query them together.
Is this possible?
(for tedious reasons I cannot/am not permitted to combine them, which would make this irrelevant!)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
假设除了具有相同的列名之外,相同的列还包含相同的数据,您希望创建一个作为所有这些表的并集的视图。
像下面这样的东西应该可以工作,但是我的 SQL 生锈了:
Assuming that in addition to having the same column names, columns of the same contain the same data, you want to create a view that is the union of all those tables.
Something like the following should work, but my SQL is rusty:
值得注意的是,您可能需要使用“union all”来保留可能存在于多个表中的唯一行。 标准联合将删除重复项。
It may be worth noting that you might need to use "union all" to preserve unique rows which may exist in more than one of the tables. A standard union will remove duplicates.
从您的查询中很难判断您是否希望数据基于 UNION 返回,或者作为包含离散列的视图返回。 这显然有效果。
考虑以下示例:
现在,对此运行以下查询:
SELECT ID, Name FROM TableA
联合所有
从表 B 中选择 ID、名称
联合所有
从 TableC 中选择 ID、名称
联合所有
SELECT ID, Name FROM TableD
这会产生以下输出:
这是您想要的吗? 如果是这样,您可以使用 UNION 查询。
现在,如果您想要的效果是获得相关数据的离散视图,您可能需要执行如下操作:
这将产生以下数据视图:
It is difficult to tell from your query whether you expect the data to be returned based on a UNION, or as a view containing the columns discretely. This obviously has an effect.
Consider the following sample:
Now, run the following query against this:
SELECT ID, Name FROM TableA
UNION ALL
SELECT ID, Name FROM TableB
UNION ALL
SELECT ID, Name FROM TableC
UNION ALL
SELECT ID, Name FROM TableD
This results in the following output:
Is this what you are after? If so, you use a UNION query.
Now, if the effect you are after is to have a discrete view of related data, you may need to do something like this:
This will result in the following view of the data:
使用联盟。
这里是解释
Use union.
Here is explanation
使用 union 语句
Use the union statement
如果你联合它们,你可以(我建议包括一些关于每条记录来自哪个表的指示符):
You can if you union them (I would suggest including some indicator as to which table each record came from):
使用 UNION ALL 而不是 UNION,除非您特别希望排除重复行。 UNION 本身需要更长的时间来执行(因为它会进行排序来查找重复项),并且会删除重复的行。
Rather than UNION, use UNION ALL, unless you specifically want duplicate rows to be excluded. UNION on its own takes longer to execute (because of the sort it does to find dupes), and removes duplicate rows.