菜鸟求一多表联合查询最大值的语句。

兵工厂三剑客 2016-07-20 12:39:39
是这样的,有8张表。任意俩表的结构都互不相同。

但是这8张表有几个字段都是一样的,如“明箱”,“暗箱”,“时间”。我现在想在这8张表中联合查询,找到时间值最大的那一行的明箱值。

我的语句是下面这样的,但是有错误:



select 明箱 from
MAC1SN,MAC2SN,MAC3SN,MAC4SN,MAC21SN,MAC22SN,MAC23SN,MAC24SN,MAC31SN,MAC32SN,MAC33SN,MAC34SN
where 时间=(select MAX(时间)
from
(
select 时间 from MAC1SN
union select 时间 from MAC2SN
union select 时间 from MAC3SN
union select 时间 from MAC4SN
union select 时间 from MAC21SN
union select 时间 from MAC22SN
union select 时间 from MAC23SN
union select 时间 from MAC24SN
union select 时间 from MAC31SN
union select 时间 from MAC32SN
union select 时间 from MAC33SN
union select 时间 from MAC34SN)
temp
)


麻烦大家帮忙改下或者帮我写出查询效率更快的。因为数据量比较庞大。
...全文
178 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
道素 2016-07-20
  • 打赏
  • 举报
回复
先分别取出每个表的最大时间的记录,都插入临时表 然后再一次取出最大时间的那行记录

IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
CREATE TABLE #t(ID INT IDENTITY(1,1),TableName NVARCHAR(500), 时间 datetime,明箱 nvarchar(1000))
insert into #t(TableName,时间,明箱)
EXEC sys.sp_MSforeachtable @command1=' select top 1 PARSENAME(''?'',1), 时间,明箱 from ? order by 时间 DESC '
,@whereand=' and charindex('',''+ object_name(object_id)+ '','','',MAC1SN,MAC2SN,MAC3SN,MAC4SN,MAC21SN,MAC22SN,MAC23SN,MAC24SN,MAC31SN,MAC32SN,MAC33SN,MAC34SN,'')>0'

SELECT TOP 1 * FROM #t ORDER BY 时间 DESC
兵工厂三剑客 2016-07-20
  • 打赏
  • 举报
回复
引用 1 楼 ap0405140 的回复:

with t as(
select 明箱,时间 from [表1]
union all
select 明箱,时间 from [表2]
union all
select 明箱,时间 from [表3]
union all
select 明箱,时间 from [表4]
union all
select 明箱,时间 from [表5]
union all
select 明箱,时间 from [表6]
union all
select 明箱,时间 from [表7]
union all
select 明箱,时间 from [表8])
select 明箱
  from t
  where 时间=(select max(时间) from t)
感谢版主。解决了。
唐诗三百首 2016-07-20
  • 打赏
  • 举报
回复

with t as(
select 明箱,时间 from [表1]
union all
select 明箱,时间 from [表2]
union all
select 明箱,时间 from [表3]
union all
select 明箱,时间 from [表4]
union all
select 明箱,时间 from [表5]
union all
select 明箱,时间 from [表6]
union all
select 明箱,时间 from [表7]
union all
select 明箱,时间 from [表8])
select 明箱
  from t
  where 时间=(select max(时间) from t)

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧