根据另一个表数据逐个从一个表中选择数据 - SQL Server 2008

时间:2014-03-27 08:53:52

标签: sql-server sql-server-2008


我有3张桌子

表1 - CommonTable

Id          Section
____________________
 1          Two-Wheeler
 2          Three-Wheeler

表2 - CategoryTbl

Id          Category                Section
___________________________________________________
 1          Two Wheeler             Two-Wheeler
 2          Three Wheeler           Three-Wheeler
 3          Four Wheeler           Four-Wheeler
 4          Other                   Others

表3 - ContentTbl

Id          CategoryId              Item
___________________________________________________
 1           1                       Bike
 2           1                       Scooter
 3           1                       Cycle
 4           2                       Car
 5           2                       Jeep
 6           4                       Truck

所需的输出是

Vehicle/Two-Wheeler/Bike
Vehicle/Two-Wheeler/Scooter
Vehicle/Two-Wheeler/Cycle
Vehicle/Three-Wheeler/Car
Vehicle/Three-Wheeler/Jeep

我试着写下面的查询

Select 'Vehicle/'+(select section from CommontTbl)+'/'+select item from 
 contenttbl where CategoryId=(select section from CommontTbl)  

我知道此查询错误,因为select section from commontbl将返回 多个值,所以如何解决这个问题,使用join或任何东西请帮我找到所需的输出

1 个答案:

答案 0 :(得分:2)

试试这个,

Select 'Vehicle/' + b.Category + '/' + a.Item from ContentTbl as a
left join CategoryTbl as b on a.CategoryId=b.ID

如果您想以CommonTbl作为基础记录,请尝试关注,

Select 'Vehicle/' + b.Category + '/' + a.Item from ContentTbl as a
left join CategoryTbl as b on a.CategoryId=b.ID
inner join CommonTable as c on c.Section = b.Section