在mysql中插入逗号分隔值

时间:2017-07-27 09:11:19

标签: mysql sql

我遇到了以下问题:

我有表'问题'(question_id,answer),其中有两列都是varchar。

输入值类似于('1,2,3','一,二,三') 我需要插入查询,我希望值插入:

1 one 
2 two
3 three

提前致谢。

3 个答案:

答案 0 :(得分:1)

按照SQl服务器

尝试此操作
DECLARE @id VARCHAR(50)= '1,2,3', 
@Answer VARCHAR(50)= 'i,know,you',
 @a VARCHAR(50), 
 @b VARCHAR(50);

WHILE LEN(@id) > 0
    BEGIN
        SET @a = LEFT(@id, CHARINDEX(',', @id+',')-1);
        SET @b = LEFT(@Answer, CHARINDEX(',', @Answer+',')-1);

        INSERT INTO #temp
        VALUES
        (@a,
         @b
        );

        SET @id = STUFF(@id, 1, CHARINDEX(',', @id+','), '');
        SET @Answer = STUFF(@Answer, 1, CHARINDEX(',', @Answer+','), '');
    END;
SELECT *
FROM #temp;
DROP TABLE #temp;

答案 1 :(得分:0)

这是正常的插入声明。

INSERT INTO questions (question_id,answer) VALUES ('1', 'one');
INSERT INTO questions (question_id,answer) VALUES ('2', 'two');
INSERT INTO questions (question_id,answer) VALUES ('3', 'three');

答案 2 :(得分:0)

SET @var1 = '1,2,3' ;
SET @var2 = 'one,two,three' ; 

DROP TEMPORARY TABLE IF EXISTS temp1; 
CREATE TEMPORARY TABLE temp1( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY , Question_Id int );

DROP TEMPORARY TABLE IF EXISTS temp2;
CREATE TEMPORARY TABLE temp2( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY , Answer VARCHAR(10) );
SET @SQL1 = CONCAT("insert into temp1 (Question_Id) values ('", REPLACE(( @var1 ), ",", "'),('"),"'); " );
SET @SQL2 =  CONCAT("insert into temp2 (Answer) values ('", REPLACE(( @var2), ",", "'),('"),"'); ");

PREPARE stmt1 FROM @SQL1;
EXECUTE stmt1;

PREPARE stmt1 FROM @SQL2;
EXECUTE stmt1;

DEALLOCATE PREPARE stmt1;

select Question_Id, Answer FROM temp1 inner join temp2 on temp1.id = temp2.id