使用where子句选择多列

时间:2012-11-21 17:24:31

标签: sql-server sql-server-2008

select
    CustomerName,City,State, MatchId,ServingSize, Fruit, DarkGreen, 
    [Red/Orange], Legumes, Starchy, Other, [Grains (oz)], 
    [Whole51%orgreater?], [Meat / Meat Alt], [Fluid Milk (cups)], Calories, 
    [Sodium (MG)], [Saturated Fat (grams)], [Trans Fat (grams)],
    MeetsAllianceForAHealthierGenerationGuidelines, OtherNotes, Name, 
    WebsiteLinkToSource, Date
from
    #FinalTempTable
Where 
    (
        MatchId,ServingSize, Fruit, DarkGreen, [Red/Orange], Legumes, Starchy, 
        Other, [Grains (oz)], [Whole51%orgreater?], [Meat / Meat Alt], [Fluid Milk (cups)],
        Calories, [Sodium (MG)], [Saturated Fat (grams)], [Trans Fat (grams)],
        MeetsAllianceForAHealthierGenerationGuidelines, OtherNotes, Name,
        WebsiteLinkToSource, Date
    )
    IN 
    (
        Select
            MatchId,ServingSize, Fruit, DarkGreen, [Red/Orange], Legumes, 
            Starchy, Other, [Grains (oz)], [Whole51%orgreater?], [Meat / Meat Alt], 
            [Fluid Milk (cups)],Calories, [Sodium (MG)], [Saturated Fat (grams)], 
            [Trans Fat (grams)], MeetsAllianceForAHealthierGenerationGuidelines, 
            OtherNotes, Name, WebsiteLinkToSource, Date
        From
            MealContributions 
        Where
            MatchId IN (Select distinct MatchId from #FinalTempTable)
    )

我正在使用此查询,但它会出现以下错误:

  

Msg 4145,Level 15,State 1,Line 10表达式为非布尔值   在预期条件的上下文中指定的类型,靠近','。

我想要来自#finaltemptable的所有列,并且只需要匹配的匹配列与#finaltemptable matchid相同的那些列#/ p>

1 个答案:

答案 0 :(得分:1)

表格

Where 
        (MatchId,ServingSize, Fruit, ... other columns .... ) 
IN 
        (... subquery with columns ...)

适用于MySQL,但不适用于SQL Server。

您必须组成一个EXISTS子句,其中列出了所有匹配的列。

 select CustomerName, City, State, MatchId, ServingSize, Fruit, DarkGreen, 
        [Red/Orange], Legumes, Starchy, Other, [Grains (oz)], 
        [Whole51%orgreater?], [Meat / Meat Alt], [Fluid Milk (cups)], Calories, 
        [Sodium (MG)], [Saturated Fat (grams)], [Trans Fat (grams)],
        MeetsAllianceForAHealthierGenerationGuidelines, OtherNotes, Name, 
        WebsiteLinkToSource, Date
   from #FinalTempTable f
  where exists (
        select *
          from MealContributions m
         where f.matchid = m.matchid AND
               f.ServingSize = m.ServingSize AND
               .... all the columns! ...)

最后一个条件

Where MatchId IN (Select distinct MatchId from #FinalTempTable))

因为您已经匹配f.matchid = m.matchid而无关紧要。