从以前的查询结果中提取文章的最新版本

ktecyv1j  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(353)

我有以下疑问:

SELECT e_c.*, c.name, j.status, j.version, j.articleId, j.title FROM assetcategory AS c
    INNER JOIN assetentries_assetcategories AS e_c 
        ON c.categoryId = e_c.categoryId AND c.name = 'news'
    INNER JOIN assetentry AS e
        ON e.entryId = e_c.entryId
    INNER JOIN journalarticle AS j
        ON j.resourcePrimKey = e.classPK
        AND e.classNameId = (SELECT classNameId FROM classname_ WHERE value = 'com.liferay.portlet.journal.model.JournalArticle')
        AND j.companyId= e.companyId
WHERE j.status = 0

返回所有类别 newsjournalarticles . 从结果中,我需要为每个项目选择最新的版本 articleId . 例如,假设有一篇文章有4个版本,即使标题不同,它也是同一篇文章,因为它将有相同的版本 articleId . 因此对于每个独特的 articleId 我需要最新的 version . 我该怎么做?

9jyewag0

9jyewag01#

向子查询添加一个联接,该子查询查找每个项目的最新版本:

SELECT e_c.*, c.name, j1.status, j1.version, j1.articleId, j1.title
FROM assetcategory AS c
INNER JOIN assetentries_assetcategories AS e_c 
    ON c.categoryId = e_c.categoryId AND c.name = 'news'
INNER JOIN assetentry AS e
    ON e.entryId = e_c.entryId
INNER JOIN journalarticle AS j1
    ON j1.resourcePrimKey = e.classPK AND
       e.classNameId = (SELECT classNameId FROM classname_
                   WHERE value = 'com.liferay.portlet.journal.model.JournalArticle') AND
       j.companyId = e.companyId
INNER JOIN
(
    SELECT articleId, MAX(version) AS max_version
    FROM journalarticle
    WHERE status = 0
    GROUP BY articleId
) j2
    ON j1.articleId = j2.articleId AND j1.version = j2.max_version;

子查询连接的基本思想 j2 上面提到的是,它将结果集限制为每篇文章的最新版本。我们不必更改查询的其余部分。

相关问题