繁体   English   中英

'on 子句'中的未知列 - 尝试了 where 和有条件但同样的错误

[英]Unknown column in 'on clause' - tried both where and having conditions but same error

SELECT hh_podcast_channel.id
FROM hh_podcast_channel
inner JOIN (
        SELECT hh_podcast_episodes.podcast_id, 
            ROW_NUMBER() OVER(PARTITION BY hh_podcast_episodes.id ORDER BY hh_podcast_episodes.published_on) as rn
        FROM hh_podcast_episodes
    ) as t2
    ON hh_podcast_channel.id = hh_podcast_episodes.podcast_id
having t2.rn = 1

#1054 - 'on 子句'中的未知列'hh_podcast_episodes.podcast_id'

您需要在 JOIN 条件中使用表别名 (t2)

SELECT hh_podcast_channel.id 
FROM hh_podcast_channel inner JOIN 
(
    SELECT hh_podcast_episodes.podcast_id, 
    ROW_NUMBER() OVER(PARTITION BY hh_podcast_episodes.id
    ORDER BY hh_podcast_episodes.published_on) as rn 
    FROM hh_podcast_episodes
) 
as t2 ON hh_podcast_channel.id = t2.podcast_id 
having t2.rn = 1

为什么你甚至在连接中使用子查询。 为简单起见,在主查询中使用row_number ,然后在子查询中使用它,如下所示:

Select id from
(SELECT t1.id,
        ROW_NUMBER() OVER(PARTITION BY t2.id ORDER BY t2.published_on) as rn
  FROM hh_podcast_channel t1
  JOIN hh_podcast_episodes t2
    On t1.id = t2.podcast_id) t
Where rn = 1

我会建议:

SELECT pc.id
FROM hh_podcast_channel pc JOIN
     (SELECT pe.*
            ROW_NUMBER() OVER (PARTITION BY pe.id ORDER BY pe.published_on) as rn
      FROM hh_podcast_episodes pe
     ) pe
     ON pc.id = pe.podcast_id
WHERE pe.rn = 1;

这解决了您的特定问题,即您的表别名被混淆了。 此外:

  • 这使用有意义的表别名,它们是列名的缩写。
  • 这将HAVING替换为WHERE 尽管两者都恰好在 MySQL 中工作,但使用HAVING具有误导性,因为它意味着聚合。
  • 这使用pe.* ,依靠优化器来选择子查询中的列。 我只是发现这样更方便,所以如果我决定包含另一列,我不必在多个地方进行更改。

我还怀疑您想要SELECT DISTINCT ,但是您的问题没有提供示例数据和所需的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM