我有 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);
最佳答案
使用自加入
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 来查找显示如何执行此操作的解决方案。
关于mysql - 如何编写简单的 MySQL 工作台查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35636299/