generated.md 1.0 KB
Newer Older
M
Mars Liu 已提交
1 2 3 4
# 生成列

Joe 需要为 Points 表

fix bug  
张志晨 已提交
5
```sql
M
Mars Liu 已提交
6 7 8 9 10 11 12 13 14
create table points(
    id int primary key auto_increment,
    x float,
    y float
)
```

增加一个生成列,保存每个点的模(modulus),即 `√(x^2 + y^2)` 。下面哪个操作是正确的?

CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
15
<br>
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
16 17

(提示)MySQL生成列的语法结构为:
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
18

CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
19 20 21 22
```sql
column_name data_type [GENERATED ALWAYS] AS (expression)
```

M
Mars Liu 已提交
23 24
<hr/>

F
feilong 已提交
25
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill){target="_blank"}。
F
feilong 已提交
26

F
feilong 已提交
27 28
* `show databases;` 列出所有数据库
* `show tables;` 列出所有表
M
Mars Liu 已提交
29

M
Mars Liu 已提交
30 31
## 答案

fix bug  
张志晨 已提交
32
```sql
33 34
alter table points add modulus double 
    generated always as (sqrt(x*x + y*y));
M
Mars Liu 已提交
35 36 37 38 39 40
```

## 选项

### A

fix bug  
张志晨 已提交
41
```sql
42 43
create generated modulus 
    on table points as (sqrt(x*x + y*y));
M
Mars Liu 已提交
44 45 46 47
```

### B

fix bug  
张志晨 已提交
48
```sql
49 50
alter table points 
    add modulus generated always as (sqrt(x*x + y*y));
M
Mars Liu 已提交
51 52 53 54
```

### C

fix bug  
张志晨 已提交
55
```sql
56 57
alter table points 
    add modulus float generated sqrt(x*x + y*y);
M
Mars Liu 已提交
58
```