【问题标题】:MYSQL: Error Code: 1054. Unknown column in 'where clause'MYSQL:错误代码:1054。“where 子句”中的未知列
【发布时间】:2018-09-13 16:01:11
【问题描述】:

我正在尝试将如下所示的外部查询中的列传递给 WHERE 子句中的内部查询,而 MySQL 不喜欢它。我不确定如何重写此查询以使其工作。

我收到的错误消息是 where 子句中的未知列 'y.DateShipped'

我想要做的是加入到内部表中的行,其 EffectiveDate 小于 DateShipped 并且也是内部联接中的最大 EffectiveDate(同一个组可以有多个行)不同的 EffectiveDate(s))

我很想知道如何让它工作或重写它以使其工作。我使用的是 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; 

【问题讨论】:

    标签: mysql sql


    【解决方案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; 
    

    【讨论】:

      【解决方案2】:

      您正在尝试一种称为横向连接的方法——而 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 ;
      

      请注意,我还将表别名更改为表名的缩写——因此查询更易于阅读。

      【讨论】:

        【解决方案3】:

        您需要在子查询中列出货件表才能正确调用它尝试:

        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; 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-19
          • 2020-11-04
          • 1970-01-01
          • 1970-01-01
          • 2011-03-22
          • 2015-09-11
          • 1970-01-01
          • 2023-02-14
          相关资源
          最近更新 更多