有问题的表格(条纹不需要的cols):
car_id INT(11) PK
url VARCHAR(100)
signup TIMESTAMP
默认列表查询如下所示:
SELECT car_id, url FROM car ORDER By signup DESC
现在我需要在结果集中找到汽车的位置,就像在列表查询中一样。和上一行和下一行的URL。
我尝试了很多不同的方法,我终于不确定它是否可行。 (在一个查询中)。
对查询的任何帮助或指向正确方向的指针都将非常感激。
修改
期望的结果将是:
pos, nextid, nexturl, previd, prevurl
答案 0 :(得分:1)
试试这个 -
+行位置
SELECT car_id, url, signup, CONCAT(pos1, '/', @p1) position FROM (
SELECT
c.*,
@p1:=@p1+1 pos1,
@p2:=IF(car_id = 3 AND @p2 IS NULL, @p1, @p2)
FROM
cars c,
(SELECT @p1:=0, @p2:=NULL) t
ORDER BY
signup
) t
WHERE
pos1 BETWEEN @p2 - 1 AND @p2 + 1
尝试此查询:
SELECT
@p2 pos,
MAX(IF(pos1 > @p2, car_id, NULL)) nextid,
MAX(IF(pos1 > @p2, url, NULL)) nexturl,
MAX(IF(pos1 < @p2, car_id, NULL)) previd,
MAX(IF(pos1 < @p2, url, NULL)) prevurl
FROM (
SELECT
c.*,
@p1:=@p1+1 pos1,
@p2:=IF(car_id = 3 AND @p2 IS NULL, @p1, @p2)
FROM
cars c,
(SELECT @p1:=0, @p2:=NULL) t
ORDER BY
signup
) t
WHERE
pos1 BETWEEN @p2 - 1 AND @p2 + 1
答案 1 :(得分:0)
(SELECT car_id, url FROM car WHERE car_id = ?)
UNION
(SELECT car_id, url FROM car WHERE signup > (SELECT signup FROM car WHERE car_id = ?) ORDER By signup ASC LIMIT 1)
UNION
(SELECT car_id, url FROM car WHERE signup < (SELECT signup FROM car WHERE car_id = ?) ORDER By signup DESC LIMIT 1)
答案 2 :(得分:0)
SELECT
@previd AS previousid,
@prevurl AS previousurl,
@previd:=@id AS currentid,
@prevurl:=@url AS currenturl,
@id:=car_id AS nextid,
@url:=url AS nexturl
FROM
(SELECT @previd:=0) AS initprevid,
(SELECT @prevurl:='') AS initprevurl,
(SELECT @id:=0) AS initid,
(SELECT @url:='') AS initurl,
car
WHERE currentid=<whatever>
ORDER BY
car.signup DESC
您可以过滤掉spurious currentid = 0