如何将多个select语句连接在一起

时间:2012-12-07 06:25:16

标签: sql sql-server

我有一个mastertable id配件CarColor变体值(1 863,862 6 2 5)等(所有id都在我的mastertable中)和另外5个像汽车颜色,变体等有价值的表


id   color
5    red
6    blue
3    green

我需要来自id = mastertable.id的每个子表的值 像

SqlCommand sqlCommand = new SqlCommand(" select * from cartable where carcolor.id = mastertable.carcolor ") ; 
SqlCommand sqlCommand = new SqlCommand(" select * from varianttable where variant.id = mastertable.variant ")  ; 
SqlCommand sqlCommand = new SqlCommand ("select * from accessoriestable where accessories.id = mastertable.accessories ") ;// 

我的问题是如何将所有5个选择语句连接在一起     或者更好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

我想你需要这个吗?

select * from mastertable
left join carcolortable on mastertable.carcolor=carcolortable.id
left join varianttable on mastertable.variant=varianttable.id
left join accessoriestable on mastertable.accessories=accessoriestable.id

如果您在评论中mastertable.carcolor(和其他人)中描述的Id中包含逗号分隔的varchar列表,那么它应该是:

select * from mastertable
left join carcolortable on 
        ( ','+mastertable.carcolor+',' 
          LIKE 
          '%,'+CAST(carcolortable.id as varchar(100))+',%'
         )
left join varianttable on 
        ( ','+mastertable.variant+',' 
          LIKE 
          '%,'+CAST(varianttable.id as varchar(100))+',%'
         )

left join accessoriestable on 
        ( ','+mastertable.accessories+',' 
          LIKE 
          '%,'+CAST(accessoriestable.id as varchar(100))+',%'
         )