mysql - 根据最后一行过滤数据 mysql

标签 mysql sql select sql-order-by having

我有这个简单的表格设置 see fiddle

    CREATE TABLE mytable
    (`id` int, `itemid` int);

    INSERT INTO mytable
    (`id`, `itemid`)
    VALUES
    (1, 111),
    (2, 222),
    (3, 333),
    (4, 444),
    (5, 111),
    (6, 222),
    (7, 333),
    (8, 564),
    (9, 111),
    (10, 121),
    (11, 131),
    (12, 111),
    (13, 353),
    (14, 373);

我想显示当前行 itemid 旁边的行中的最后一个 itemid。 我已经用下面的方法做到了

    SELECT 
    mt.id,
    mt.itemid,
    (
        select mt2.itemid
        from mytable mt2
        where mt2.id < mt.id
        ORDER BY mt2.id DESC
        LIMIT 1
    ) as lastitemid
     FROM mytable mt 
     ORDER BY id DESC
     LIMIT 5

这按预期返回

    ID  ITEMID  LASTITEMID
    14  373     353
    13  353     111
    12  111     131
    11  131     121
    10  121     111

但是我只想显示 lastitemid = 111 的行。

我试过

    SELECT 
    mt.id,
    mt.itemid,
    (
        select mt2.itemid
        from mytable mt2
        where mt2.id < mt.id
        ORDER BY mt2.id DESC
        LIMIT 1
    ) as lastitemid
    FROM mytable mt 
    WHERE lastitemid = 111
    ORDER BY id DESC
    LIMIT 5

在“where 子句”中获取未知列“lastitemid”

我也试过添加

    AND mt2.itemid = 111

内部查询

这没有得到任何错误,但为所有行返回 111,这不是我想要的,因为它是无效的,例如对于 id=12,lastitemid 是 131,但它说 111

    ID  ITEMID  LASTITEMID
    14  373     111
    13  353     111
    12  111     111
    11  131     111
    10  121     111

使用我的示例数据集,如果我的查询正确,我应该得到以下结果

    ID  ITEMID  LASTITEMID
    13  353     111
    10  121     111
    6   222     111
    2   222     111

我怎样才能做到这一点?

最佳答案

试试这个:

SELECT mt.id, mt.itemid,
      (SELECT mt2.itemid FROM mytable mt2 WHERE mt2.id < mt.id ORDER BY mt2.id DESC LIMIT 1) AS lastitemid
FROM mytable mt 
HAVING lastitemid = 111
ORDER BY id DESC
LIMIT 5

检查 SQL FIDDLE DEMO

输出

| ID | ITEMID | LASTITEMID |
|----|--------|------------|
| 13 |    353 |        111 |
| 10 |    121 |        111 |
|  6 |    222 |        111 |
|  2 |    222 |        111 |

关于mysql - 根据最后一行过滤数据 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21059021/

相关文章:

C# select 不改变数组的值

c++ - 连接器/C++ MySQL 错误代码 : 2014 , SQLState : HY000 and Commands out of sync error why?

java - 如何使用jdbc代码手动连接mysql?

sql - Oracle Top-N 查询 : are results guaranteed to be ordered?

C# LINQ 生成 "Specified cast is not valid"错误

javascript - 根据选择更改选定值

mysql - 如何将 IN 谓词编写为 NOT IN 谓词

mysql - 使用选项值设置搜索条件的变量

java - Netbeans GUI 和 SQL 问题

mysql - 如何从两个表中随机选择异常(exception)?