我有1个包含3列的表。 id(auto_increment),column0,column1如下:
+----+--------+---------+
| id | column0| column1 |
+----+--------+---------+
| 1 | 1.1111 | 0.1111 |
| 2 | 1.2222 | 0.2222 |
| 3 | 1.3333 | 0.3333 |
| 4 | 1.4444 | 0.4444 |
| . | 1.5555 | 0.5555 |
+----+--------+---------+
我想选择这个:
+--------+---------+
| column0| column1 |
+--------+---------+
| 1.1111 | 0.2222 |
| 1.2222 | 0.3333 |
| 1.3333 | 0.4444 |
| 1.4444 | 0.5555 |
| 1.5555 | 0.5555 |
+--------+---------+
如何将这两个查询连接到一个查询中? 有人可以为我编写代码。
SELECT column0 FROM table;
和第二个查询
SELECT column1 FROM table where id >1
union all
(SELECT column1 FROM table
ORDER BY id DESC 1);
答案 0 :(得分:0)
使用自我加入
SELECT t1.column0, IFNULL(t2.column1, t1.column1) AS column1
FROM table AS t1
LEFT JOIN table AS t2 ON t1.id = t2.id - 1
处理最后一行需要LEFT JOIN
和IFNULL
。你也可以用UNION
SELECT t1.column0, t2.column1
FROM table AS t1
INNER JOIN table AS t2 ON t1.id = t2.id - 1
UNION
(SELECT column0, column1
FROM table
ORDER BY id DESC
LIMIT 1)
请注意,这只适用于id
序列中没有间隙的情况。当存在间隙时找到下一行更复杂。您可以搜索SO以获取显示如何执行此操作的解决方案。
答案 1 :(得分:0)
如果我正确地关注你,你想要将column0或下一行的一行和一列作为单个记录返回,但除了逻辑“下一个排序的行”之外,没有链接它们的“键”。 / p>
如果这是正确的,请尝试这个。
select t1.column0, t2.column1 from
(select @t1row := @t1row + 1 as t1row, x1.column0 from (select @t1row := 0) as r1, tablex as x1 order by id) as t1,
(select @t2row := @t2row + 1 as t2row, x2.column1 from (select @t2row := 0) as r2, tablex as x2 where x2.id != (select min(x3.id) from tablex as x3) order by id) as t2
where t1.t1row = t2.t2row;
这应该返回:
column0 column1
1.1111 0.2222
1.2222 0.3333
1.3333 0.4444
1.4444 0.5555
但是这使得我们没有“最后”行的第0列和“第一”行的第1列。处理基于您想要完成的事情。 1)不要包括它们 2)再返回一行,将last.column0与first.column1连接起来 3)返回一行,其中last.column0链接到空列1,另一行返回空列column0链接到first.column1
如果#1,你实际上已经完成了。
如果是#2,请将此union子句添加到上面的查询中:
union
select x1.column0, x2.column1
from tablex as x1, tablex as x2, (select min(xi.id) as minid, max(xi.id) as maxid from tablex as xi) as x3
where x1.id = x3.maxid and x2.id = x3.minid
你得到:
column0 column1
1.1111 0.2222
1.2222 0.3333
1.3333 0.4444
1.4444 0.5555
1.5555 0.1111
如果是#3,请将这些union子句添加到上面的查询中:
union
select x1.column0, null as column1 from tablex as x1 where x1.id = (select max(xi.id) from tablex as xi)
union
select null as column0, x2.column1 from tablex as x2 where x2.id = (select min(xi.id) from tablex as xi)
你得到了(你可以随意使用它们):
column0 column1
1.1111 0.2222
1.2222 0.3333
1.3333 0.4444
1.4444 0.5555
1.5555
0.1111
享受!