首页 > 解决方案 > 使用 case 语句在 mariadb 中创建虚拟列失败

问题描述

我正在尝试create a table in MariaDB使用virtual columncase语句定义的

这就是我所拥有的

create table Foto (
  ID int AUTO_INCREMENT not null primary key,
  LigPlaatsCode varchar(10) not null,
  FotoTypeID int not null check (FotoType in (0, 1, 2, 3)),
  Foto varchar(1000) not null,
  FotoType varchar(50) as
    case FotoTypeID 
         when 0 then 'Bidprent'
         when 1 then 'Krantartikel'
         when 2 then 'Persoon'
         else 'Graf'
    end,     `

  constraint FK_Foto_LigPlaats foreign key (LigPlaatsCode) references LigPlaats (LigPlaatsCode) 
)

但是它总是给我这个错误

#42000您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以获取正确的语法,以便在第 7 行时使用
'case FotoTypeID
when 0 then 'Bidprent'
when 1 then 'Krantar'

当我在谷歌上搜索如何创建虚拟列和案例时,我发现的链接似乎表明我做对了,但显然我没有。所以我错过了一些东西。
这个创建表语句有什么问题?

编辑
我的版本是10.3.21-MariaDB

标签: mariadb

解决方案


生成的列需要围绕 case 表达式的括号:

create table Foto (
  ID int AUTO_INCREMENT not null primary key,
  LigPlaatsCode varchar(10) not null,
  FotoTypeID int not null ,
  Foto varchar(1000) not null,
   FotoType varchar(50) as
    (case FotoTypeID 
         when 0 then 'Bidprent'
         when 1 then 'Krantartikel'
         when 2 then 'Persoon'
         else 'Graf'
    end), -- brackets around
  -- constraint as separate entry because it is referencing FotoType
  constraint fototypecheck check (FotoType in (0, 1, 2, 3))
);

db<>小提琴演示


此行没有意义,因为 FotoType 是文本:

FotoTypeID int not null check (FotoType in (0, 1, 2, 3)),
-- probably it should be
FotoTypeID int not null check (FotoTypeID in (0, 1, 2, 3)),

推荐阅读