1

我有一张下表。

ID Name State Date
1   A1   First 1/10/2013
2   A1   Second 1/11/2013
3   A1   Last   1/12/2013
4   A2   First  1/10/2013
5   A2   Closed 1/11/2013
6   A3   First  1/10/2012
7   A3   Second 1/10/2012

状态的优先顺序如下

 1 First
 2 Second
 3 Last
 4 Closed

这意味着我必须只显示名称的最新状态(前提是状态未关闭。如果状态关闭,我不必显示该 ID)。

所以上表的输出应该是

ID Name State Date
3  A1    Last  1/12/2013
7  A3    Second 1/10/2012

我不确定如何进行?如果我知道的话,我会尝试一些东西,但现在我正在努力解决它。我可以这样做php并将输出存储在另一个中table/view并显示它,但它必须在数据库中完成。

谢谢

4

2 回答 2

1

假设您ID是 auto_incremented。

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  name, MAX(ID) max_ID
            FROM    tableName
            GROUP   BY Name
        ) b ON  a.ID = b.max_ID AND
                a.Name = b.Name
WHERE   a.State <> 'Closed'

或者如果列日期的数据类型是DATE

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  name, MAX(date) max_date
            FROM    tableName
            GROUP   BY Name
        ) b ON  a.ID = b.max_date AND
                a.Name = b.Name
WHERE   a.State <> 'Closed'

于 2013-02-01T01:31:10.157 回答
0

我也提出了这样的解决方案,但我不确定我的是否更快。

SELECT * FROM 
    (SELECT id, name, state, date FROM myTable ORDER BY state DESC, id DESC) AS subQuery
WHERE state <> 'Closed' GROUP BY name

EDIT: I tried it this way because GROUP BY will only return you the first item, not the last one, so by first ordering it to put first the one you look for then grouping them, you get it!

于 2013-02-01T01:46:05.530 回答