MySQL:使用JOIN获得仅具有最近子行的父行

问题描述 投票:0回答:1

我有3张桌子:

  • 新闻(news别名tn
  • 新闻类别(news_cat别名tc
  • 新闻图片(news_pic别名tp

我需要获取最新的新闻,每个新闻都有其类别,并且只有该特定帖子的第一张图片,使用o作为顺序字段。

这是我当前的SQL查询:

SELECT
tn.date_news AS date_news,
tn.title AS title,
tn.text AS text,
tn.url AS url,
tc.name AS cat,
tp.file AS file
FROM news AS tn
JOIN news_cat AS tc ON tc.id_cat = tn.id_cat
JOIN (
    SELECT file FROM news_pic WHERE news_pic.id_news = tn.id_news ORDER BY temp.o LIMIT 1
) AS tp ON tp.id_news = tn.id_news
WHERE
tn.flg_featured = 1
ORDER BY tc.date_news DESC LIMIT 6

我收到此错误消息:

Column not found: 1054 Unknown column 'tn.id_news' in 'where clause'

This is the sqlfiddle具有表的结构和一些示例数据。感谢您的任何建议。

mysql join
1个回答
2
投票

这是greatest-n-per-group问题;您需要为o的每个值找到id_news的最小值,然后在与该最小值匹配的JOIN值上将news_pic o本身找出来以获得第一张图片。请注意,您还有其他一些错误(tc.flg_featured应该为tn.flg_featuredtc.date_news应该为tn.date_news)。这应该给您想要的结果:

© www.soinside.com 2019 - 2024. All rights reserved.