我试图将如下所示的外部查询中的列传递给WHERE子句中的内部查询,而MySQL不喜欢它。我不确定如何重写此查询以使其工作。
我收到的错误消息是 where子句中的未知列'y.DateShipped'
我要执行的操作是使用小于DateShipped的EffectiveDate联接到内部表中的行,并且也是内部联接中的最大EffectiveDate(对于同一组,可以有多个行,通过不同的有效日期)
我很想知道如何使它起作用或重写它以便起作用。我正在使用MySQL 5.6,因此我没有可用的窗口函数,否则我认为这可以工作。
select
x.id,
y.id,
y.DateShipped
from Shipment y inner join
(select id, SourceId, DestinationId, SourcePPFContractId, EffectiveDate
from Relationship where EffectiveDate <= y.DateShipped order by
EffectiveDate desc limit 1) x
on x.DestinationId = y.DestinationCustomerId
and x.SourceId = y.OriginCustomerId
and x.SourcePPFContractId = y.OriginContractId;
答案 0 :(得分:1)
首先执行内部选择(来自“关系”),然后与第一次选择合并。这就是为什么它不起作用。您应该将DateShipped移到第一个选择项的where子句中:
select
x.id,
y.id,
y.DateShipped
from Shipment y inner join
(select id, SourceId, DestinationId, SourcePPFContractId, EffectiveDate
from Relationship order by
EffectiveDate desc limit 1) x
on x.DestinationId = y.DestinationCustomerId
and x.SourceId = y.OriginCustomerId
and x.SourcePPFContractId = y.OriginContractId
and x.EffectiveDate <= y.DateShipped;
答案 1 :(得分:0)
您需要在子查询中列出发货表才能正确调用它:
select
x.id,
y.id,
y.DateShipped
from Shipment y inner join
(select id, SourceId, DestinationId, SourcePPFContractId, EffectiveDate
from Relationship, Shipment where EffectiveDate <= Shipment.DateShipped order by
EffectiveDate desc limit 1) x
on x.DestinationId = y.DestinationCustomerId
and x.SourceId = y.OriginCustomerId
and x.SourcePPFContractId = y.OriginContractId;
答案 2 :(得分:0)
您正在尝试一种称为横向联接的方法-MySQL不支持这种方法。因为只需要一列,所以可以使用相关的子查询:
select (select r.id
from Relationship r
where r.DestinationId = s.DestinationCustomerId and
r.SourceId = s.OriginCustomerId and
r.SourcePPFContractId = s.OriginContractId and
r.EffectiveDate <= s.DateShipped
order by r.EffectiveDate desc
limit 1
) as x_id,
s.id, s.DateShipped
from Shipment s ;
请注意,我还将表别名更改为表名的缩写-这样查询就更易于阅读。