如何在查询中正确实现JOIN/UNION ALL,从数据库中选择所有表的列?

huangapple go评论60阅读模式
英文:

How to properly implement JOIN/ UNION ALL in a query when selecting columns from all tables in a database?

问题

I'm trying to select all tables with their max value of TimeLoaded. TimeLoaded is a timestamp. So my output should be similar to this:

我尝试选择所有表格及其TimeLoaded的最大值。TimeLoaded是一个时间戳。因此,我的输出应该类似于这样:

英文:

Assume I have many tables in a database.

如何在查询中正确实现JOIN/UNION ALL,从数据库中选择所有表的列?

I'm trying to select all tables with their max value of TimeLoaded. TimeLoaded is a timestamp. So my output should be similar to this:

如何在查询中正确实现JOIN/UNION ALL,从数据库中选择所有表的列?

Since I am trying to select every table in the database while retrieving the max value of TimeLoaded, I am unsure how to implement JOIN and UNION ALL as there may be a database with 20 or more tables.

答案1

得分: 1

SELECT TOP (1) MAX(TimeLoaded) as TimeLoaded, 'Arrival' AS Tables FROM [your_db_name].[dbo].[Arrival]
Union
SELECT TOP (1) MAX(TimeLoaded) as TimeLoaded, 'Duration' AS Tables FROM [your_db_name].[dbo].[Duration]
Union
SELECT TOP (1) MAX(TimeLoaded) as TimeLoaded, 'Departure' AS Tables FROM [your_db_name].[dbo].[Departure]
Union
SELECT TOP (1) MAX(TimeLoaded) as TimeLoaded, 'Alert' AS Tables FROM [your_db_name].[dbo].[Alert]

英文:

I do not know how to select table name, but maybe you can try this:

 SELECT TOP (1) MAX(TimeLoaded) as TimeLoaded, 'Arrival' AS Tables FROM [your_db_name].[dbo].[Arrival]
 Union 
 SELECT TOP (1) MAX(TimeLoaded) as TimeLoaded, 'Duration' AS Tables FROM [your_db_name].[dbo].[Duration]
 Union 
 SELECT TOP (1) MAX(TimeLoaded) as TimeLoaded, 'Departure' AS Tables FROM [your_db_name].[dbo].[Departure]
 Union 
 SELECT TOP (1) MAX(TimeLoaded) as TimeLoaded, 'Alert' AS Tables FROM [your_db_name].[dbo].[Alert]

huangapple
  • 本文由 发表于 2023年7月3日 09:59:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定