我必须通过3个表与文件和类别建立一对多关系,我的表架构如下所示:
类别表
CREATE TABLE `categories` (
`id` INT(3) NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(25) NOT NULL,
`visible_name` VARCHAR(25) NOT NULL,
`is_active` TINYINT(1) NOT NULL,
PRIMARY KEY (`id`),
INDEX `idx_file_category_visible_name_colum` (`visible_name`)
)
ENGINE = INNODB;
文件表
CREATE TABLE `files` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`title` VARCHAR(200) NOT NULL,
`filename` VARCHAR(255) NOT NULL,
`description` TEXT NOT NULL,
`date_uploaded` BIGINT(20) DEFAULT 0,
`last_updated` BIGINT(20) DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_unique_file` (`filename`)
)
ENGINE = INNODB;
file_categories表
CREATE TABLE `file_categories` (
`fkfile` BIGINT(20) NOT NULL,
`fkcategory` INT(3) NOT NULL,
PRIMARY KEY (`fkfile`, `fkcategory`),
FOREIGN KEY (`fkfile`)
REFERENCES files (`id`)
ON UPDATE CASCADE
ON DELETE RESTRICT,
FOREIGN KEY (`fkcategory`)
REFERENCES categories (`id`)
ON UPDATE CASCADE
ON DELETE RESTRICT
)
ENGINE = INNODB;
以下是我用来测试的示例数据:
INSERT INTO `stackoverflow_qst`.`files` (`id`, `title`, `filename`, `description`, `date_uploaded`, `last_updated`) VALUES (NULL, 'First Dummy File', 'fdf.pdf', 'Just a dummy file', '1552295385043', '0');
INSERT INTO `stackoverflow_qst`.`categories` (`id`, `category_name`, `visible_name`, `is_active`) VALUES (NULL, 'Category 1', 'Category One', '1'), (NULL, 'Category 2', 'Category Two', '2'), (NULL, 'Category 3', 'Category Three', '1');
INSERT INTO `stackoverflow_qst`.`file_categories` (`fkfile`, `fkcategory`) VALUES ('1', '1'), ('1', '2'), ('1', '3');
选择文件时,希望选择该文件的所有类别ID作为逗号分隔的列,并带有我的选择查询文件,如下所示:
SELECT f.id, f.title, f.filename, f.description, f.date_uploaded, f.last_updated,
GROUP_CONCAT(DISTINCT fc.fkcategory ORDER BY fc.fkcategory ASC ) AS categories_ids
FROM `files` AS f
INNER JOIN `file_categories` AS fc ON (fc.fkfile = f.id)
GROUP BY fc.fkfile
它将正确返回其他列,但category_ids列除外,该列返回预览时有错误的BLOB,如以下屏幕快照所示: categories_ids column BLOB preview Query Result in PHPMyAdmin
我已经继续以逗号分隔的形式查询file_categories表,但它仍然像往常一样返回一个blob。我在StackOverflow上查找了相关问题,我的查询似乎还可以,其中一些查询是: MySQL : Multiple row as comma separated single row(这里的答案非常直接,甚至指向MySql Doc), MYSQL comma separated IDs vs separate table,以及 SQL Join multiple ids comma separated,但我仍然遇到相同的问题,这与我使用的MySql版本有关吗?
当前为MySql 5.1.41版,严格用于要在其上部署当前项目的服务器。