我试图在我的 sql 服务器上运行以下查询:
CREATE TABLE `e_store`.`products`(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(250) NOT NULL ,
`brand_id` INT UNSIGNED NOT NULL ,
`category_id` INT UNSIGNED NOT NULL ,
`attributes` JSON NOT NULL ,
PRIMARY KEY(`id`) ,
INDEX `CATEGORY_ID`(`category_id` ASC) ,
INDEX `BRAND_ID`(`brand_id` ASC) ,
CONSTRAINT `brand_id` FOREIGN KEY(`brand_id`) REFERENCES `e_store`.`brands`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE ,
CONSTRAINT `category_id` FOREIGN KEY(`category_id`) REFERENCES `e_store`.`categories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE
);
Run Code Online (Sandbox Code Playgroud)
我的 e_store 数据库中已经有品牌和类别表。
但我收到以下错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'JSON NOT NULL ,
PRIMARY KEY(`id`) ,
INDEX `CATEGORY_ID`('category_id' ' at line 6
Run Code Online (Sandbox Code Playgroud)
小智 11
对于那些面临与我类似的问题的人:
MariaDB 本身并未实现 JSON 数据类型,但LONGTEXT出于兼容性原因,它将其用作别名。根据文档(https://mariadb.com/kb/en/library/json-data-type/):
JSON 是为了
LONGTEXT与 MySQL 的JSON数据类型兼容而引入的别名。MariaDB 实现了这一点LONGTEXT,因为 JSON 数据类型与 SQL 标准相矛盾,而 MariaDB 的基准测试表明性能至少是等效的。为了确保插入一个有效的 json 文档,可以使用 JSON_VALID 函数作为 CHECK 约束。
因此,如果您JSON对 MariaDB 中的数据类型有疑问,只需使用LONGTEXT. ;-)
您在索引定义中给出了单引号而不是反引号
尝试这个:
CREATE TABLE `e_store`.`products`(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(250) NOT NULL ,
`brand_id` INT UNSIGNED NOT NULL ,
`category_id` INT UNSIGNED NOT NULL ,
`attributes` JSON NOT NULL ,
PRIMARY KEY(`id`) ,
INDEX `CATEGORY_ID`(`category_id` ASC) , -- Changed single quotes to backticks
INDEX `BRAND_ID`(`brand_id` ASC) , -- Changed single quotes to backticks
CONSTRAINT `brand_id` FOREIGN KEY(`brand_id`) REFERENCES `e_store`.`brands`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE ,
CONSTRAINT `category_id` FOREIGN KEY(`category_id`) REFERENCES `e_store`.`categories`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE
);
Run Code Online (Sandbox Code Playgroud)