查询将2个差异表中的记录提取到2列

时间:2012-12-21 11:09:40

标签: sql sql-server database

我有两张如下表:

1)

    Engine
    ======

ID     Title    Unit   Value
123    Hello    Inch   50
555    Hii      feet   60

2)

    Fuel
    =====

ID    Title     Value
123   test12     343
555   test5556   777

我希望根据给定的ID在2列中选择结果(两个表中的ID应该相同):

标题 -- This will get the (Title + Unit) from Engine table and only Title from Fuel table. Value

-- This will get Value from both tables.

ID = 123的结果是:

Title          Value

Hello(Inch)   50
test12        343

有关如何在SQL Server 2008中获取此内容的任何建议。

4 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

查看SQL JOIN:INNER JOIN,LEFT JOIN等

Select 
      e.ID, e.Title, e.Unit, e.Value, f.Title as FuelTitle, e.Value as FuelValue,
      e.Title+' '+e.Units As TitleAndUnits
From Engine e
Join Fuel f
On e.ID = f.ID

答案 2 :(得分:0)

你可以在没有联接的情况下这样做,但是根据你的情况下的其他因素,加入它可能会更加优化。

没有加入的例子:

select concat(t1.c1, ' ', t1.c2, ' ', t2.c1) col1, concat(t1.c3, ' ', t2.c3) col2 
from t1, t2
where t1.id = [ID] and t2.id = [ID]

答案 3 :(得分:0)

根据您的相同数据和所需结果,您似乎希望使用UNION ALL从两个表中获取数据:

select title+'('+Unit+')' Title, value
from engine
where id = 123
union all
select title, value
from fuel
where id = 123

请参阅SQL Fiddle with Demo

查询结果为:

|       TITLE | VALUE |
-----------------------
| Hello(Inch) |    50 |
|      test12 |   343 |