2016-02-25 49 views
0

我有一個3列的表。 ID(AUTO_INCREMENT),column0,COLUMN1這樣的:如何編寫簡單的MySQL工作臺查詢

+----+--------+---------+ 
| 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

沒有。有什麼鏈接1.1111和0.2222?或者其他任何值?事實上,你必須有一些邏輯背後的邏輯。僅僅是採用兩個結果集並將它們放在一起? –

+0

您還將此標記爲mysql-workbench,這是因爲您只關心輸出,而不是查詢?如果是這樣,請複製並粘貼! –

+0

值不鏈接。每次值都會有所不同。我想有一個查詢不是兩個。如何在一個查詢中連接這兩個查詢? – tomtom

回答

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 JOINIFNULL需要處理的最後一行。你也可以用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) 

DEMO

請注意,這僅適用於是否有在id順序沒有間隙做。當存在差距時尋找下一行更加複雜。您可以搜索SO以瞭解如何執行此操作的解決方案。

0

如果我正確地關注你,你想要將下一行的column0或one row和column1作爲單個記錄返回,但除了邏輯「下一個已排序的行」之外沒有鏈接它們的「關鍵字」。

如果這是正確的,試試這個。

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 

但是,這會使得我們失去了「第一」行的「最後」行和列1的column0。處理是基於你想要完成的。 1)不要包含它們 2)返回一個將last.column0連接到first.column1的行 3)返回last.column0的一行鏈接到空列1,另一行的空column0鏈接到first.column1

如果#1,你實際上完成了。

如果#2,這個工會子句添加到上述查詢:

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 

享受!