我有一个 MySQL GROUP_CONCAT .... INSERT 问题 此代码有效:
SELECT group_concat(tabel2.img_name separator ',')
FROM tabel2
GROUP BY tabel2.produit_id
我需要将结果插入到另一个表中,但我卡住了。
这个(或我能想到的任何组合)不起作用
INSERT INTO tabel1.imgname
SELECT group_concat(tabel2.img_name separator ',')
FROM tabel2
GROUP BY tabel2.produit_id
WHERE tabel1.product_id = tabel2.produit_id
我做错了什么?
CREATE TABLE IF NOT EXISTS `tabel1` (
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`rubrique_id` int(11) NOT NULL,
`marque_id` int(11) NOT NULL,
`subfamily_id` int(11) NOT NULL,
`product_name` varchar(150) NOT NULL,
`imgname` varchar(255) DEFAULT NULL,
`product_description1` text NOT NULL,
`product_description2` text NOT NULL,
`product_order` int(11) NOT NULL,
`product_page` int(11) NOT NULL,
`price_min` float NOT NULL,
PRIMARY KEY (`product_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0;
INSERT INTO `tabel1` (`product_id`, `rubrique_id`, `marque_id`, `subfamily_id`, `product_name`, `imgname`, `product_description1`, `product_description2`, `product_order`, `product_page`, `price_min`)
VALUES
(33, 15, 23, 40, 'product 1', NULL, '', '', 0, 0, 0),
(34, 13, 13, 13, 'product 2', NULL, '', '', 0, 0, 0),
(35, 14, 14, 14, 'product 3', NULL, '', '', 0, 0, 0);
CREATE TABLE IF NOT EXISTS `tabel2` (
`img_id` int(11) NOT NULL AUTO_INCREMENT,
`img_name` text NOT NULL,
`article_id` int(11) DEFAULT NULL,
`produit_id` int(11) DEFAULT NULL,
`product_select` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`img_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4018 ;
INSERT INTO `tabel2` (`img_id`, `img_name`, `article_id`, `produit_id`, `product_select`)
VALUES
(4013, 'acoacki086050.jpg', 13342, 33, NULL),
(4014, '32252il6jh2dqex.jpg', NULL, 34, NULL),
(4015, '33265ulrzmgr18w.jpg', NULL, 34, NULL),
(4016, '40334zcfk0c4n67.jpg', NULL, 35, NULL),
(4017, '40473frd4900u82.jpg', NULL, 35, NULL);
所以说 tabel1.product_id = 34 我需要 tabel1.imgname = 32252il6jh2dqex.jpg,33265ulrzmgr18w.jpg
最佳答案
我想这就是你想要做的:
INSERT INTO tabel1 (product_id,imgname)
SELECT tabel2.produit_id, group_concat(tabel2.img_name separator ',') as imgname
FROM tabel2
GROUP BY tabel2.produit_id
更新:感谢您发布架构并阐明要求。
这应该适合你:
UPDATE tabel1
INNER JOIN
(
SELECT tabel2.produit_id, group_concat(tabel2.img_name separator ',') AS imgname
FROM tabel2
GROUP BY tabel2.produit_id
) s ON s.produit_id = tabel1.product_id
SET tabel1.imgname = s.imgname;
关于mysql - mysql GROUP_CONCAT 和 INSERT 到另一个表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10339542/