我有这个简单的表格设置 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
输出
| ID | ITEMID | LASTITEMID |
|----|--------|------------|
| 13 | 353 | 111 |
| 10 | 121 | 111 |
| 6 | 222 | 111 |
| 2 | 222 | 111 |
关于mysql - 根据最后一行过滤数据 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21059021/