所以这里的情况是,我在数据库中有4个表,即:
" question_info":CREATE TABLE
question_info
(
q_id
mediumint(9) NOT NULL,
q_type_id
int(11) NOT NULL,
q_options_id
mediumint(9) NOT NULL,
q_category_id
int(11) NOT NULL,
q_text
varchar(2048) NOT NULL,
status
tinyint(4) NOT NULL DEFAULT '0',
q_date_added
date NOT NULL DEFAULT '2013-01-01',
q_difficulty_level
tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY(q_id)
);
" question_options_info&#34 ;:
question_info
" question_answer_info&#34 ;:
q_id
" trivia_data&#34 ;:
q_type_id
所以我需要的是,将数据插入q_options_id
表。
此查询返回数据:
q_category_id
此查询将返回如下数据:
我已尝试使用此特定查询来插入数据:
q_text
但它始终会返回此错误:
status
老实说,我是SQL的新手。所以请尽可能简单地解释一下。 任何帮助,将不胜感激。 谢谢。
答案 0 :(得分:6)
您不需要VALUES
关键字,因为您从查询中进行选择:
INSERT INTO trivia_data (
q_id,
q_text,
q_options_1,
q_options_2,
q_options_3,
q_options_4,
q_options,
q_difficulty_level,
q_date_added)
SELECT
question_info.q_id,
question_info.q_text,
question_options_info.q_options_1,
question_options_info.q_options_2,
question_options_info.q_options_3,
question_options_info.q_options_4,
question_answer_info.q_options,
question_info.q_difficulty_level,
question_info.q_date_added
FROM question_info
JOIN question_options_info on question_info.q_options_id = question_options_info.q_options_id
JOIN question_answer_info on question_info.q_id = question_answer_info.q_id;
通常,如果要插入记录,则语法为
INSERT INTO <tablename> (<column1>, <column2>, ..., <columnN>)
VALUES (<value1>, <value2>, ..., <valueN>)
如果要插入结果,语法如下:
INSERT INTO <tablename> (<column1>, <column2>, ..., <columnN>)
SELECT <value1>, <value2>, ..., <valueN> FROM ...
如您所见,此案例中没有VALUES
个关键字
答案 1 :(得分:1)
从SQL中删除VALUES
,因为在这种情况下值来自SELECT。
INSERT INTO trivia_data (
q_id,
q_text,
q_options_1,
q_options_2,
q_options_3,
q_options_4,
q_options,
q_difficulty_level,
q_date_added
)
SELECT
question_info.q_id,
question_info.q_text,
question_options_info.q_options_1,
question_options_info.q_options_2,
question_options_info.q_options_3,
question_options_info.q_options_4,
question_answer_info.q_options,
question_info.q_difficulty_level,
question_info.q_date_added
FROM question_info
JOIN question_options_info
ON question_info.q_options_id = question_options_info.q_options_id
JOIN question_answer_info
ON question_info.q_id = question_answer_info.q_id;
答案 2 :(得分:0)
删除VALUES
关键字。试试这个:
INSERT INTO trivia_data (q_id, q_text, q_options_1, q_options_2,
q_options_3, q_options_4, q_options, q_difficulty_level, q_date_added)
SELECT question_info.q_id, question_info.q_text,
question_options_info.q_options_1, question_options_info.q_options_2,
question_options_info.q_options_3, question_options_info.q_options_4,
question_answer_info.q_options, question_info.q_difficulty_level,
question_info.q_date_added FROM question_info
JOIN question_options_info on question_info.q_options_id = question_options_info.q_options_id
JOIN question_answer_info on question_info.q_id = question_answer_info.q_id;