我有这个简单的表格设置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
我怎样才能做到这一点?
答案 0 :(得分:2)
试试这个:
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 |
答案 1 :(得分:1)
如果保证id是连续的,你可以这样做。
SELECT curr.id, curr.itemid, previous.itemid AS lastitemid
FROM mytable curr JOIN mytable previous ON previous.id = curr.id - 1
WHERE previous.itemid = 111
否则,你需要像
这样的东西SELECT curr.id, curr.itemid, previous.itemid AS lastitemid
FROM mytable curr, mytable previous
WHERE previous.id < curr.id
AND previous.itemid = 111
AND NOT EXISTS (
SELECT 1 FROM mytable interloper
WHERE interloper.id < curr.id
AND previous.id < interloper.id )
答案 2 :(得分:1)
您只需将当前查询用作表格,然后使用where子句从中进行选择。
SELECT
l.id,
l.itemid
FROM
(
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
) As l
WHERE l.lastitemid = 111
ORDER BY l.id DESC
LIMIT 5