MYSQL 如何将虚拟列添加到现有 table

MYSQL How to add virtual column into existing table

我下面有这个 'data' table,其中 'INITIAL','BETWIXT','ENDING' 列插入了值;

SET SQL_SAFE_UPDATES = 0;

CREATE TABLE data (
    INITIAL INT NOT NULL,
    BETWIXT INT NOT NULL,
    ENDING VARCHAR(20)
);

INSERT 
    INTO data(data.INITIAL,data.BETWIXT,data.ENDING) 
    VALUES
    (30,40,"N0"), 
    (60,80,"N1"), 
    (90,120,"N2"),
    (120,160,"N3"),
    (150,200,"N4"); 

SELECT DISTINCT ENDING AS "HI"
    FROM data
    WHERE data.INITIAL BETWEEN 60 AND 150;

但我正打算将“HI”虚拟列插入到主 table 'data' 中,以便将其可视化为

INITIAL  BETWIXT  ENDING  HI 

30       40      N0     N1

60       80      N1     N2

90       120     N2     N3

120      160     N3     N4
 
150      200     N4

除了单个虚拟列,我该如何编写代码来构建上述内容?

您是否希望获取 HI 列中结束列的下一个值。 如果是这样,可以使用 LEAD。

select initial,BETWIXT,ending,lead(ending) over (order by initial) hi from data;

参考fiddle here.

你的输出示例不正确,因为第一行你应该得到一个空值,而不是 'N1'。关于您的问题,只需列出查询中的所有列即可:

select t.initial,
t.betwixt,
t.ending,
case when t.initial between 60 and 150 then t.ending else NULL end as 'HI'
from data t;

如果你真的需要间隔1步的输出,那么请看@Pankaj的代码post