2017-10-05 69 views
1

我有一個表結構如下:如何將兩個別名添加到通過MySql查詢創建的表中?

year 
---------- 
1995 
2000 
2010 

*(前三行)

我想創建一個「差異」列其使用輸入年份:

ind | year | diff 
----------------- 
    1 | 1995 | 0 
    2 | 2000 | 5 
    3 | 2010 | 10 

爲了做到這一點,我試圖創建和ind列和修改這裏建議:http://www.mysqltutorial.org/mysql-tips/mysql-compare-calculate-difference-successive-rows/

雖然我不成功w第i個給第二別名我已經創建表:

SET @row_number = 0; 

SELECT 
     g1.ind 
    (g2.year - g1.year) AS diff 
FROM (
     select * from 
         (SELECT 
          (@row_number:[email protected]_number + 1) AS ind, year 
         FROM 
          movies) t 

) g1 
INNER JOIN 
g1 g2 ON g2.ind = g1.ind + 1 

的錯誤是: 錯誤代碼:1146表「db_name.g1」不存在

+0

ID始終是連續的? – Strawberry

+0

我已經重新編輯我的問題 - 實際上沒有,因此我創建了一個連續的id列但是現在我有問題將別名添加到我創建的表 – Bugu

+0

因此,您想要創建一個diff列和ind列? – Strawberry

回答

0
DROP TABLE IF EXISTS my_table; 

CREATE TABLE my_table 
(year INT NOT NULL PRIMARY KEY); 

INSERT my_table VALUES 
(1995),(2000),(2010); 

例如爲:

SELECT x.year 
    , x.year - COALESCE(MAX(y.year),x.year) diff 
    FROM my_table x 
    LEFT 
    JOIN my_table y 
    ON y.year < x.year 
GROUP 
    BY x.year; 
+------+------+ 
| year | diff | 
+------+------+ 
| 1995 | 0 | 
| 2000 | 5 | 
| 2010 | 10 | 
+------+------+ 
3 rows in set (0.01 sec) 

......或者......

SELECT year 
    , COALESCE([email protected],0) diff 
    , @prev:=year 
    FROM my_table 
    , (SELECT @prev:=null) vars 
ORDER 
    BY year; 
+------+------+-------------+ 
| year | diff | @prev:=year | 
+------+------+-------------+ 
| 1995 | 0 |  1995 | 
| 2000 | 5 |  2000 | 
| 2010 | 10 |  2010 | 
+------+------+-------------+ 
0

我不知道,如果你有點過分複雜的事情。

試試這個:

SELECT 
    m1.id, 
    m1.year, 
    IFNULL(m1.year - m2.year, 0) AS diff 
FROM 
    movies m1 
LEFT JOIN 
    movies m2 ON m2.id +1 = m1.id 
ORDER BY id ASC 

其輸出(使用數據)

|id|year|diff| 
+--+----+----+ 
|1 |1995| 0 | 
|2 |2000| 5 | 
|3 |2010| 10 | 

如果id不存在,也不需要產生,我們只是包裹在m2.year diff字段加上max

SELECT 
    m1.year, 
    IFNULL((m1.year - max(m2.year)),0) AS diff 
FROM movies m1 
LEFT JOIN 
    movies m2 on m1.year > m2.year 
GROUP BY m1.year 

...然後加入年份。這給:

|year|diff| 
+----+----+ 
|1995| 0 | 
|2000| 5 | 
|2010| 10 | 
+0

謝謝!我編輯了我的問題,以更好地解釋我正在處理的問題。你可以建議一個解決方案,而不是電影表我需要使用選擇查詢的結果表?在這種情況下,我無法提供別名 – Bugu

相關問題