MySQL |最多选择两个一个表中的值

时间:2017-03-06 18:09:22

标签: mysql sql

我有身份证(电视连续剧ID),T(译者身份证),S(季节),E(剧集)

我需要转换它:

| ID | T | S | E |  
| 1  | 1 | 1 | 2 |  
| 1  | 1 | 1 | 3 |  
| 1  | 2 | 1 | 3 |  
| 2  | 3 | 2 | 1 |  
| 2  | 3 | 3 | 1 |  

进入这个:

| ID | T | S | E |  
| 1  | 1 | 1 | 3 |  
| 1  | 2 | 1 | 3 |  
| 2  | 3 | 3 | 1 |  

我的想法:

SELECT `ID, `T`, `S`, `E`
FROM `UPDATE`
WHERE
`S` = (SELECT MAX(`S`) FROM `UPDATE` WHERE `ID` = `ID`)
AND `E` = (SELECT MAX(`E`) FROM `UPDATE` WHERE `ID` = `ID` AND `S` = (SELECT MAX(`S`) FROM `UPDATE` WHERE `ID` = `ID`))
GROUP BY `ID`, `T`
ORDER BY `TIMESTAMP` DESC

2 个答案:

答案 0 :(得分:0)

我认为这会奏效。您需要首先确定每个ID和T的最大值S.一旦确定了这些ID,您就可以加入所有三个字段的原始表格以获得最大值E.

   SELECT A.ID, A.T, A.S, MAX(B.E) as E
    FROM (
    SELECT ID, T, MAX(S) AS S
    FROM `UPDATE` U
    GROUP BY ID, T) A
    INNER JOIN `UPDATE` B
    ON A.ID = B.ID AND A.T = B.T AND A.S = B.S
    GROUP BY A.ID, A.T, A.S

答案 1 :(得分:0)

使用not exists()获取每对id,tmax()的最新季节,以获取最新一集。

select id, t, s, max(e) as e
from tbl
where not exists (
  select 1
  from tbl as i
  where i.id = tbl.id
    and i.t  = tbl.t
    and i.s  > tbl.s
    )
group by id, t, s

或使用left join作为:

select tbl.id, tbl.t, tbl.s, max(tbl.e) as e
from tbl 
  left join tbl i
    on i.id = tbl.id
      and i.t  = tbl.t
      and i.s  > tbl.s
where i.id is null
group by tbl.id, tbl.t, tbl.s;

rextester演示:http://rextester.com/LAFPS18322

返回

+----+---+---+---+
| id | t | s | e |
+----+---+---+---+
|  1 | 1 | 1 | 3 |
|  1 | 2 | 1 | 3 |
|  2 | 3 | 3 | 1 |
+----+---+---+---+