【发布时间】:2014-01-11 05:53:37
【问题描述】:
我有这个简单的表格设置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
我怎样才能做到这一点?
【问题讨论】:
-
在黑暗中刺伤,但我的第一个想法是不知何故使用 GROUP BY?
标签: mysql sql select sql-order-by having