一 表结构:
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`brands` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', 'a,b,c', 'liu,jian,fu', '23');
INSERT INTO `student` VALUES ('2', 'e,f', 'jian,kk', '34');
结果图:
需要对name,brands字段的数据,通过逗号进行分割,第一行应该是:1*3*3=9;第二行应该是:1*2*2=4,总共因该有13条数据
二 编写语句:
select c.id ,brands,name from (
SELECT a.id as id,
substring_index( substring_index( a.name, ',', b.help_topic_id + 1 ), ',',- 1 ) name
FROM student a
JOIN mysql.help_topic b ON b.help_topic_id < (length( a.name ) - length( REPLACE ( a.name, ',', '' ) ) + 1)
ORDER BY a.id ) as c ,
(
SELECT a.id as id,
substring_index( substring_index( a.brands, ',', b.help_topic_id + 1 ), ',',- 1 ) brands
FROM student a
JOIN mysql.help_topic b ON b.help_topic_id < (length( a.brands ) - length( REPLACE ( a.brands, ',', '' ) ) + 1)
ORDER BY a.id
) as d where c.id=d.id group by id,brands,name
结果: