MySQL: Select 个值可用

MySQL: Select penult values

有 2 个表:

表 1:

id  |phone| order|
 ---|-----|------|
  1 | 122 |  6   |
  2 | 122 |  4   |
  3 | 122 |  3   |
  4 | 123 |  6   |
  5 | 123 |  5   |
  6 | 123 |  3   |   
  7 | 124 |  6   |
  8 | 124 |  5   |
  9 | 125 |  6   |
  10| 125 |  5   |

表 2:

|phone |
|------|
|122   |
|123   |
|124   |

我必须 select id 和最后一个订单根据下一个条件:

所以结果应该是:

|phone  | order|
|------ |------|
|122    | 4    |
|123    | 5    |
|124    | 5    |

MySQL 版本:Ver 15.1 Distrib 5.5.64-MariaDB

你的mariadb版本有点旧

Thta 将使用按 order 列排序的行号,它 select 仅第二个。

需要子查询中的 LIMIT,因为 mariadb 遵循标准并且不会对子查询进行排序select。

CREATE TABLE Table1
    (`id` int, `order` int)
;
    
INSERT INTO Table1
    (`id`, `order`)
VALUES
    (122, 6),
    (122, 4),
    (122, 3),
    (123, 6),
    (123, 5),
    (123, 3),
    (124, 6),
    (124, 5),
    (125, 6),
    (125, 5)
;
CREATE TABLE Table2
    (`id` int)
;
    
INSERT INTO Table2
    (`id`)
VALUES
    (122),
    (123),
    (124)
;
SELECT id,`order`
FROM (SELECT 

 t1.`order`
, IF ( @id = t1.id ,@rn := @rn +1, @rn:= 1) AS rownum
, @id := t1.`id` as id
FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id = t2.id,(SELECT @id := 0,@rn := 0) t3
ORDEr BY t1.id,t1.`order` DESC LIMIT 18446744073709551615) t4
WHERE rownum = 2
    
 id | order
--: | ----:
122 |     4
123 |     5
124 |     5

db<>fiddle here

基本上你想看最后两条记录;如果最后一条记录有顺序 3,则使用前一条。

那将是一个带有 window 函数的简单查询 and/or 横向连接,因为您的旧 MySQL 版本不支持这些功能。用户变量是一个选项,如 nbk 所示,但它们使用起来很棘手 - MySQL 8.0 宣布此功能将在未来版本中弃用。

我将推荐相关子查询和一些逻辑:

select t2.id,
    coalesce(
        nullif((select ord from table1 t1 where t1.id = t2.id order by odering_id desc limit 1), 3),
        (select ord from table1 t1 where t1.id = t2.id order by odering_id desc limit 1, 1)
    ) as ord
from table2 t2

第一个子查询获取最新值; nullif() 检查 returned 值和 returns null 是否有顺序 3;这表明 coalesce() 它应该 return 第二个子查询的结果,即获取先前的值。

order是语言关键字,所以我用ord代替。

Demo in MySQL 5.5:

 id | ord
--: | --:
122 |   4
123 |   5
124 |   5