use*_*156 5 mysql select nested
id title slug summary ------------------------------ 1 title1 slug1 summary1 2 title2 slug2 summary2 3 title3 slug3 summary3 4 title4 slug4 summary4
我正在尝试选择所有字段,同时选择上一行/下一行的id,title和slug
SELECT
title, slug, summary, id as current_id,
(SELECT id FROM table WHERE id < current_id ORDER BY id DESC LIMIT 1) AS prev_id,
(SELECT title FROM table WHERE id < current_id ORDER BY id DESC LIMIT 1) AS prev_title,
(SELECT slug FROM table WHERE id < current_id ORDER BY id DESC LIMIT 1) AS prev_slug,
/*
(SELECT id ... ) AS next_id
(SELECT title...) AS next_title
...
and if there are more fields to select, I have to repeat this (SELECT...)
*/
FROM
table
WHERE
id IN (2,3,4);
Run Code Online (Sandbox Code Playgroud)
查询有效,但显然这不是明智的方法.
有些人可以帮忙简化一下吗?谢谢
小智 0
您可以从一个子查询中提取列:
SELECT
title, slug, summary, id as current_id, prev.prev_id, prev.prev_title, prev.prev_slug, next.next_id, next.next_title, next.next_slug
FROM
table,
(SELECT id AS prev_id, title AS prev_title, slug AS prev_slug FROM table WHERE id < 2 ORDER BY id DESC LIMIT 1) AS prev,
(SELECT id AS next_id, title AS next_title, slug AS next_slug FROM table WHERE id > 2 ORDER BY id DESC LIMIT 1) AS next
WHERE
id = 2;
Run Code Online (Sandbox Code Playgroud)
IN
但如果你必须在 where 中使用子句,这就行不通了;您需要对id
...的每个值运行此查询