将两个SQL查询合并为一个

时间:2014-04-11 00:16:40

标签: sql sql-server-2008

我正在尝试合并两个SQL查询(它们都独立工作):

查询#1:

select 
    N1."DateAndTime",
    N0."Ration" 
from 
    (("dbo"."AnimalFeedDailyConsumption" N0 
inner join 
    "dbo"."AnimalHistoricalData" N1 on (N0."OID" = N1."OID")) 
left join 
    "dbo"."BasicAnimal" N2 on (N1."BasicAnimal" = N2."OID"))
where 
    (N1."LactationNumber" = 4) and (N1."GCRecord" is null and (N2."Number" = 511))

查询#2:

select 
   N2."Number",
   N1."DIM",
   N1."DateAndTime",
   N1."LactationNumber",
   N0."TotalYield"
from 
   (("dbo"."DailyMilk" N0 
inner join 
   "dbo"."AnimalHistoricalData" N1 on (N0."OID" = N1."OID")) 
left join 
   "dbo"."BasicAnimal" N2 on (N1."BasicAnimal" = N2."OID"))
where 
   (N1."LactationNumber" = 4) and (N1."GCRecord" is null and (N2."Number" = 511))

我尝试过此操作,导致' Ration'

的空值
select 
    N2."Number",
    N1."DIM",
    N1."DateAndTime",
    N1."LactationNumber",
    N0."TotalYield",
    N3."Ration"
from 
    (("dbo"."DailyMilk" N0 
inner join 
    "dbo"."AnimalHistoricalData" N1 on (N0."OID" = N1."OID")) 
left join 
    ("dbo"."AnimalFeedDailyConsumption" N3 
inner join 
    "dbo"."AnimalHistoricalData" N1 on (N3."OID" = N1."OID"))
left join 
    "dbo"."BasicAnimal" N2 on (N1."BasicAnimal" = N2."OID"))
where 
    (N1."LactationNumber" = 4) and (N1."GCRecord" is null and (N2."Number" = 511))

然后我尝试了这个,这也导致了' Ration':

select 
   N2."Number",
   N1."DIM",
   N1."DateAndTime",
   N1."LactationNumber",
   N0."TotalYield",
   N3."Ration"
from
   (("dbo"."DailyMilk" N0 
inner join 
   "dbo"."AnimalHistoricalData" N1 on (N0."OID" = N1."OID")) 
left join 
   "dbo"."AnimalFeedDailyConsumption" N3 on (N3."OID" = N1."OID")
left join 
   "dbo"."BasicAnimal" N2 on (N1."BasicAnimal" = N2."OID"))
where 
   (N1."LactationNumber" = 4) and (N1."GCRecord" is null and (N2."Number" = 511))

1 个答案:

答案 0 :(得分:0)

这很难回答,因为我不知道你们桌子之间的关系。在“工作”查询中,您正在测试RIGHT表(N2)上的条件,您使用LEFT OUTER加入它是因为它是可选的 - 也许这是正确的,但看起来不正确。

如何将所有连接转换为内部连接?:

select 
  N2."Number",
  N1."DIM",
  N1."DateAndTime",
  N1."LactationNumber",
  N0."TotalYield",
  N3."Ration"
from "dbo"."DailyMilk" N0 
inner join "dbo"."AnimalHistoricalData" N1       on N0."OID" = N1."OID" 
inner join "dbo"."AnimalFeedDailyConsumption" N3 on N3."OID" = N1."OID"
inner join "dbo"."BasicAnimal" N2                on N1."BasicAnimal" = N2."OID"
where N1."LactationNumber" = 4 
and   N1."GCRecord" is null 
and   N2."Number" = 511

样式评论: BTW很难(对我来说)理解哪个表是N0,N1,N3和& N3。为什么不把它们称为BA,AHD,DM和AFDC?此外,太多(多余)括号。

注意:由于我没有您的表格或数据,因此无法对此进行测试。你怎么创建一个SQLfiddle?