简体   繁体   English

如何连接两个不同表的列

[英]how to join columns of two different tables

i have two tables called overview and current_voltage.我有两个表,称为概述和 current_voltage。 i want to get top 1 record of two different tables in a single table output.我想在单个表 output 中获得两个不同表的前 1 条记录。

sql query sql 查询

    select top 1  VL1,VL2,VL3 from current_voltage
    where deviceimei ='233'
    order by devicetimestamp desc      
    union
    select top 1  OTI,WTI,ATI from overview
    where deviceimei ='233'
    order by devicetimestamp desc

req op请求操作

VL1,VL2,VL3,OTI,WTI,ATI
234,235,234,25,24,25

A simple JOIN would do.一个简单的 JOIN 就可以了。 Here we go:这里我们 go:

SELECT TOP 1 cv.VL1, cv.VL2, cv.VL3, ov.OTI, ov.WTI, ov.ATI
FROM current_voltage cv
JOIN overview ov
ON cv.deviceimei = ov.deviceimei
WHERE cv.deviceimei ='233'
ORDER BY cv.devicetimestamp DESC, ov.devicetimestamp DESC

To read more about JOIN in sql, refer this要阅读有关 sql 中的 JOIN 的更多信息,请参阅

You need a cross join of the 2 queries:您需要 2 个查询的交叉连接:

select t1.*, t2.*
from (    
    select top 1  VL1,VL2,VL3 from current_voltage
    where deviceimei ='233'
    order by devicetimestamp desc      
) t1 cross join (
    select top 1  OTI,WTI,ATI from overview
    where deviceimei ='233'
    order by devicetimestamp desc
) t2

You can also use lateral join:您还可以使用横向连接:

select vc.*, ov.*
from current_voltage cv cross apply
     (select top (1) ov.*
      from overview ov
      where ov.deviceimei = cv.deviceimei 
      order by ov.devicetimestamp  desc
     ) ov 
where ov.deviceimei ='233'
order by cv.devicetimestamp  desc;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM