You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MariaDB创建Passenger表时CHECK约束语法错误求助

解决MariaDB创建Passenger表的SQL语法错误

错误原因分析

  1. 约束语法不合法:定义PassID的primary key后未加逗号分隔,直接写constraint导致语法报错;且列级约束中命名check的格式不符合MariaDB规范。
  2. LIKE匹配规则不兼容:MariaDB的LIKE不支持[A-Z][0-9]这类字符范围匹配模式(该写法适用于SQL Server),需改用正则匹配实现需求。

修正后的代码

方案1:列级约束(不命名check约束)

/*=====Table Passenger=====*/
create table Passenger(
    PassID char(6) not null primary key,
    check (PassID REGEXP '^[A-Z]{3}[0-9]{3}$'),
    PassName varchar(100) not null,
    No_KTP int not null,
    Adress varchar(100) not null,
    No_Telp varchar(20) not null
);

方案2:表级约束(命名check约束)

如果需要明确命名约束,用表级约束写法更规范:

/*=====Table Passenger=====*/
create table Passenger(
    PassID char(6) not null primary key,
    PassName varchar(100) not null,
    No_KTP int not null,
    Adress varchar(100) not null,
    No_Telp varchar(20) not null,
    constraint chk_PassID check (PassID REGEXP '^[A-Z]{3}[0-9]{3}$')
);

补充说明

  • REGEXP '^[A-Z]{3}[0-9]{3}$' 实现的逻辑和你原本的[A-Z][A-Z][A-Z][0-9][0-9][0-9]完全一致:严格匹配3个大写字母加3个数字的6位字符串。
  • 若你的MariaDB版本低于10.2.1,默认会忽略CHECK约束,需在配置中开启sql_mode包含STRICT_TRANS_TABLES或CHECK_CONSTRAINTS才能让约束生效。

内容的提问来源于stack exchange,提问作者Rayhan Alfarizi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:45:05