我想从表AnswerSets中插入数据
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| Id | int(11) | YES | | NULL | |
| Q1 | int(11) | YES | | NULL | |
| Q2 | int(11) | YES | | NULL | |
| Q3 | int(11) | YES | | NULL | |
[...]
+-------+---------+------+-----+---------+-------+
到T_ANSWER_SET。
+--------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| U_ID | int(11) | YES | | NULL | |
| Q_ID | int(11) | YES | | NULL | |
| ANSWER | int(11) | YES | | NULL | |
+--------+---------+------+-----+---------+-------+
因此我在一个过程的循环中使用以下查询:
INSERT INTO T_ANSWER_SET (U_ID, Q_ID, ANSWER)
SELECT i, j, (SELECT c FROM AnswerSets WHERE Id = i);
i
,j
是整数,并且在循环中递增。 c
是我想要数据的AnswerSets列的名称(如' Q10')。但我总是这样:
+------+------+--------+
| U_ID | Q_ID | ANSWER |
+------+------+--------+
| 1 | 1 | 0 |
| 1 | 2 | 0 |
| 1 | 3 | 0 |
[...]
+------+------+--------+
我希望查询针对i = 3,j = 10和c =' Q10':
INSERT INTO T_ANSWER_SET (U_ID, Q_ID, ANSWER)
SELECT 3, 10, (SELECT Q10 FROM AnswerSets WHERE Id = 3);
提前感谢您的帮助。
答案 0 :(得分:0)
MariaDB [(none)]> SET @`i` := 3,
-> @`j` := 1,
-> @`c` := '`Q10`';
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> SET @`stmt` := CONCAT('
'> INSERT INTO `T_ANSWER_SET` (`U_ID`, `Q_ID`, `ANSWER`)
'> SELECT ', @`i`, ', ', @`j`, ', (SELECT ', @`c`, '
'> FROM `AnswerSets`
'> WHERE `Id` = ', @`i`, ')
'> ');
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> SELECT @`stmt`;
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| @`stmt` |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|
INSERT INTO `T_ANSWER_SET` (`U_ID`, `Q_ID`, `ANSWER`)
SELECT 3, 1, (SELECT `Q10`
FROM `AnswerSets`
WHERE `Id` = 3)
|
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
MariaDB [(none)]> -- PREPARE `stmt` FROM @`stmt`;
MariaDB [(none)]> -- EXECUTE `stmt`;
MariaDB [(none)]> -- DEALLOCATE PREPARE `stmt`;