考虑更改您的架构。每个字段都应该是原子的 - 具有一个值。
创建一个爱好表,更改用户表,添加一个表以启用用户和爱好之间的多对多关系。创建一个显示用户爱好的视图。
这意味着您将能够执行类似的查询。
select * from `hobby` ; -- means your hobby check box can now be created dynamically
select * from `username_hobby` where username_id = 1 ; -- means you already have the username hobbies as separate elements.
有关数据规范化的更多详细信息 => https://www.google.com.au/search?q=atomic+data+normalization
sqlfiddle 示例http://sqlfiddle.com/#!2/5cdef/1/0
建议的架构如下。
DROP TABLE IF EXISTS `hobby`;
CREATE TABLE `hobby` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`hobby` varchar(31) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `hobby` (`id`, `hobby`)
VALUES
(1,'reading'),
(2,'painting'),
(3,'gaming');
DROP TABLE IF EXISTS `username`;
CREATE TABLE `username` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(31) DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `username` (`id`, `username`)
VALUES
(1,'abc');
DROP VIEW IF EXISTS `username_hobbies_view`;
CREATE TABLE `username_hobbies_view` (
`username` VARCHAR(31) DEFAULT '',
`hobby` VARCHAR(31) DEFAULT NULL,
`username_id` INT(11) UNSIGNED NOT NULL,
`hobby_id` INT(11) UNSIGNED NOT NULL
) ENGINE=MyISAM;
DROP TABLE IF EXISTS `username_hobby`;
CREATE TABLE `username_hobby` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username_id` int(11) unsigned NOT NULL,
`hobby_id` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `username_relationship` (`username_id`),
KEY `hobby_relationship` (`hobby_id`),
CONSTRAINT `hobby_relationship` FOREIGN KEY (`hobby_id`) REFERENCES `hobby` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `username_relationship` FOREIGN KEY (`username_id`) REFERENCES `username` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `username_hobby` (`id`, `username_id`, `hobby_id`)
VALUES
(1,1,1),
(2,1,2);
DROP TABLE `username_hobbies_view`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `username_hobbies_view`
AS SELECT
`username`.`username` AS `username`,
`hobby`.`hobby` AS `hobby`,
`username_hobby`.`username_id` AS `username_id`,
`username_hobby`.`hobby_id` AS `hobby_id`
FROM ((`username` join `username_hobby` on((`username`.`id` = `username_hobby`.`username_id`))) join `hobby` on((`hobby`.`id` = `username_hobby`.`hobby_id`)));