【发布时间】:2018-01-15 07:22:42
【问题描述】:
使用 SQL Server,我有两个带有 Where 子句的 Select 语句,但不断得到重复的结果。我的第一个查询是:
SELECT
PricingContingencies.*,
Terms.*,
rscDescription AS RateScheme,
ptyAbbreviation AS PointTypeAbbreviation,
FAKs.*,
fat.*
FROM ((((PricingContingencies
INNER JOIN Terms ON pcoTerms = terID)
INNER JOIN PointTypes ON pcoPointTypeFK = ptyID)
LEFT JOIN RateSchemes ON pcoRateSchemeFK = rscID)
LEFT JOIN FAKs ON fakPricingContingencyFK = pcoID)
LEFT JOIN FuelAgreementTypes fat ON ftyID = pcoFuelAgreementTypeFK
WHERE pcoPricingAgreementFK = 61523 and pcoID = 16490608
并返回两行(这是正确的)。
我的第二个查询非常相似,但有额外的列(唯一的区别是“LEFT JOIN PalletPricing ON pprPricingContingenciesFK = pcoID)”而不是“LEFT JOIN FAKs ON fakPricingContingencyFK = pcoID)”:
SELECT
PricingContingencies.*,
Terms.*,
rscDescription as RateScheme,
ptyAbbreviation as PointTypeAbbreviation,
PalletPricing.*,
fat.*
FROM ((((PricingContingencies
INNER JOIN Terms ON pcoTerms = terID)
INNER JOIN PointTypes ON pcoPointTypeFK = ptyID)
LEFT JOIN RateSchemes ON pcoRateSchemeFK = rscID)
LEFT JOIN PalletPricing ON pprPricingContingenciesFK = pcoID)
LEFT JOIN FuelAgreementTypes fat ON ftyID = pcoFuelAgreementTypeFK
WHERE pcoPricingAgreementFK = 61523 and pcoID = 16490608
并返回6行(这也是正确的)。
如何将它们组合起来,总共得到 8 行?如果我使用 INNER JOIN 将它们组合起来,例如:
SELECT
FirstSet.*,
SecondSet.*
FROM (
SELECT
PricingContingencies.*,
Terms.*,
rscDescription AS RateScheme,
ptyAbbreviation AS PointTypeAbbreviation,
FAKs.*,
fat.*
FROM ((((PricingContingencies
INNER JOIN Terms ON pcoTerms = terID)
INNER JOIN PointTypes ON pcoPointTypeFK = ptyID)
LEFT JOIN RateSchemes ON pcoRateSchemeFK = rscID)
LEFT JOIN FAKs ON fakPricingContingencyFK = pcoID)
LEFT JOIN FuelAgreementTypes fat ON ftyID = pcoFuelAgreementTypeFK
WHERE pcoPricingAgreementFK = 61523 and pcoID = 16490608
) as FirstSet
INNER JOIN
(
SELECT
PricingContingencies.*,
Terms.*,
rscDescription as RateScheme,
ptyAbbreviation as PointTypeAbbreviation,
PalletPricing.*,
fat.*
FROM ((((PricingContingencies
INNER JOIN Terms ON pcoTerms = terID)
INNER JOIN PointTypes ON pcoPointTypeFK = ptyID)
LEFT JOIN RateSchemes ON pcoRateSchemeFK = rscID)
LEFT JOIN PalletPricing ON pprPricingContingenciesFK = pcoID)
LEFT JOIN FuelAgreementTypes fat ON ftyID = pcoFuelAgreementTypeFK
WHERE pcoPricingAgreementFK = 61523 and pcoID = 16490608
) as SecondSet
ON FirstSet.pcoID = SecondSet.pcoID
ORDER BY FirstSet.pcoPriority DESC
我得到 12 行 PalletPricing 列重复且不正确(第二个结果加倍 [6 x 2])。如何将它们组合起来,以便得到正确的 8 行(2 + 6)?
提前致谢。
【问题讨论】:
-
您基本上是在寻找 UNION 查询。但是,UNION(或其更具包容性的兄弟,UNION ALL)要求两个查询具有完全相同的列数,并且每列中的数据类型大致相同。除非 PalletPricing 和 Faks 具有相同的表布局,否则有时您将不得不返回假数据,并且来自两个来源中的每一个的列名将设置为您从顶级查询中输出的任何列名。
-
它们真的是重复的吗?可能至少有一列不同。
-
你是对的,一栏是不同的。如何排除那个不同的列,使整行不包含在查询中?
标签: sql sql-server select inner-join where-clause