每个类别的每个ID的最高状态

时间:2015-01-26 12:59:17

标签: mysql

我正在努力解决以下问题:

我有一个名为Article_Statuses的表(以及主表文章,ArticleID为p.key)并具有以下结构

ID, ArticleID, Status, Status_Date, Category

在此表中,我收集了每个类别(预定义)文章的所有状态(ArticleID),每个类别的最高ID是该类别的最新状态,以及一些数据:

1, BB0001, LFS, 15-01-2015, LIC
2, BB0001, LFA, 19-01-2015, LIC
3, BB0001, SA, 10-01-2015, FIS
4, BB0001, CA, 19-01-2015, FIS
5, BB0002, LFS, 10-01-2015, LIC
6, BB0002, LFA, 11-01-2015, LIC
7, BB0003, CA, 19-01-2015, FIS

我想使用以下结果进行查询:

ArticleID, Status LIC, Status_Date LIC, Status FIS, Status_Date FIS
BB0001, LFA, 19-01-2015, CA, 19-01-2015
BB0002, LFA, 11-01-2015, ,
BB0003, , , CA, 19-01-2015

我发现以下解决方案仅适用于一个类别,我坚持添加其他类别......

SELECT `a`.`ArticleID`, `b`.`Status_Date` AS `LIC_Date`, `b`.`Status` AS `LIC_Status`
FROM `Articles` `a` 
    INNER JOIN `Article_Statuses` `b` ON `a`.`ArticleID` = `b`.`ArticleID`
    INNER JOIN ( SELECT `ArticleID`, MAX( `ID` ) `MAXID`
    FROM `Article_Statuses`
    WHERE `Category` = 'LIC' GROUP BY `ArticleID` ) `c`
    ON `b`.`ArticleID` = `c`.`ArticleID` AND `b`.`ID` = `c`.`MAXID`
WHERE `a`.`Partner` = 10
GROUP BY `a`.`ArticleID` 
ORDER BY `a`.`ArticleID` ASC 

2 个答案:

答案 0 :(得分:0)

这是返回所需结果的查询:

select a.articleid, 
       b.status_date as LIC_Date, b.status as LIC_Status, 
       c.status_date as FIS_Date, c.status as FIS_Status  
from Articles a
left join Article_Statuses b on b.ArticleID =a.articleid and 
     b.id = (select max(id) from Article_Statuses ast 
             where ast.articleid=a.articleid and ast.category='LIC')
left join Article_Statuses c on c.ArticleID =a.articleid and 
    c.id = (select max(id) from Article_Statuses ast 
             where ast.articleid=c.articleid and ast.category='FIS')
order by a.articleid

我使用左连接,因为不是每个文章都存在两个类别。

答案 1 :(得分:0)

" Partner"是什么意思?在你的查询?你之前没有提到它,所以我猜它并不重要。

您有多少个不同的类别?只有两个或更多?我问,因为以这种方式返回数据远非快速和最佳。

这将是:

SELECT 
  a.ArticleID, 
  b.Status_Date AS LIC_Date, b.Status AS LIC_Status,
  d.Status_Date AS FIS_Date, d.Status AS FIS_Status
FROM Articles AS a 
    INNER JOIN Article_Statuses AS b ON a.ArticleID = b.ArticleID
    INNER JOIN ( 
        SELECT ArticleID, MAX( ID ) AS ID
        FROM Article_Statuses
        WHERE Category = 'LIC' GROUP BY ArticleID
    ) AS c ON b.ArticleID = c.ArticleID AND b.ID = c.ID

    INNER JOIN Article_Statuses AS d ON a.ArticleID = d.ArticleID
    INNER JOIN ( 
        SELECT ArticleID, MAX( ID ) AS ID
        FROM Article_Statuses
        WHERE Category = 'FIS' GROUP BY ArticleID
    ) AS e ON d.ArticleID = e.ArticleID AND d.ID = e.ID

WHERE a.Partner = 10
ORDER BY a.ArticleID ASC 

基本上你只是用不同的别名重复连接 - 我用过" d"和" e"但最好使用像" LIC_category"而不只是" b"。

如果您的示例中某些类别可能为空,那么您还应该使用左连接而不是内连接。