使用INSERT SELECT和VALUES插入MYSQL数据库

时间:2015-07-02 19:30:54

标签: mysql select insert

这里我试图在表中插入一个新行(调用)。我试图获得的唯一值是来自调用者表的caller_id,其余的都是我已经拥有的字符串。

我不确定我做错了什么。如果我没有弄错的话,caller_id是一个外键。

                        string initialcalls = "INSERT INTO calls (is_outbound, is_active, start_time, dealer_no, caller_id,call_id, is_spam, is_voicemail) SELECT"
                            + "'@is_outbound', '@is_active', '@start_time', '@dealer_no', @caller_id, '@call_id',  '@is_spam', '@is_voicemail' FROM callers WHERE callers.id = @fone;";
                        MySqlCommand initialCall = new MySqlCommand(initialcalls, connection);
                        string dealerNO = Regex.Match(items[10], @"\d+").Value;



                        initialCall.Parameters.AddWithValue("@is_outbound", isOutBound);
                        initialCall.Parameters.AddWithValue("@is_active", is_active);
                        initialCall.Parameters.AddWithValue("@start_time", datetimeSQLstart);

                        initialCall.Parameters.AddWithValue("@dealer_no", dealerNO);
                        initialCall.Parameters.AddWithValue("@caller_id", selectforcallerid);
                        initialCall.Parameters.AddWithValue("@call_id", items[0]);
                        initialCall.Parameters.AddWithValue("@fone", items[8]);

                        initialCall.Parameters.AddWithValue("@is_spam", isSpam);
                        initialCall.Parameters.AddWithValue("@is_voicemail", isVoiceMail);


                        initialCall.ExecuteNonQuery();

                        this.CloseConnection();

1 个答案:

答案 0 :(得分:0)

插入和选择必须在两个完全独立的查询中完成。

INSERT INTO tablename (field1, field2) VALUES (value1, value2);

SELECT field1, field2 FROM tablename WHERE something > something else;

您必须引用外表以使用外键。

SELECT table1.field1, table1.field2 FROM table1, table2 
WHERE table1.id = table2.id
相关问题