我正在尝试从表B的结果集中插入表A:
INSERT INTO A (x, y, created_at)
(SELECT x, "something", a_timestamp
FROM B WHERE c IS NULL AND a_timestamp > NOW())
问题是,对于某些情况
(SELECT x, "something", a_timestamp
FROM B WHERE c IS NULL AND a_timestamp > NOW())
不返回任何记录(可以),但是其他INSERT失败。
如何从这种情况中掩饰自己?
谢谢!
答案 0 :(得分:0)
我无法重现错误:
mysql> DROP TABLE IF EXISTS `tbl_test`;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `tbl_test` (
-> `id` TINYINT
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `tbl_test`
-> SELECT 1
-> FROM DUAL
-> WHERE 0 = 0;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> SELECT `id` FROM `tbl_test`;
+------+
| id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
mysql> INSERT INTO `tbl_test`
-> SELECT 1
-> FROM DUAL
-> WHERE 0 = 1;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SELECT `id` FROM `tbl_test`;
+------+
| id |
+------+
| 1 |
+------+
1 row in set (0.00 sec)
<强>更新强>
mysql> DROP TABLE IF EXISTS `tbl_test`;
Query OK, 0 rows affected (0.00 sec)
mysql> CREATE TABLE IF NOT EXISTS `tbl_test` (
-> `id` TINYINT
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO `tbl_test`
-> (`id`)
-> VALUES
-> (101);
Query OK, 1 row affected (0.00 sec)
mysql> SELECT `id`
-> FROM `tbl_test`;
+------+
| id |
+------+
| 101 |
+------+
1 row in set (0.00 sec)
mysql> INSERT INTO `tbl_test`
-> SELECT `id` + 1
-> FROM `tbl_test`
-> WHERE `id` > 100;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> SELECT `id`
-> FROM `tbl_test`;
+------+
| id |
+------+
| 101 |
| 102 |
+------+
2 rows in set (0.00 sec)
mysql> INSERT INTO `tbl_test`
-> SELECT `id` + 1
-> FROM `tbl_test`
-> WHERE `id` < 100;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SELECT `id`
-> FROM `tbl_test`;
+------+
| id |
+------+
| 101 |
| 102 |
+------+
2 rows in set (0.00 sec)
请参阅db-fiddle。
答案 1 :(得分:0)
您可以使用INSERT IGNORE INTO
解决您的问题。
例如:
INSERT IGNORE INTO A (x, y, created_at)
(SELECT x, "something", a_timestamp
FROM B WHERE c IS NULL AND a_timestamp > NOW())
可以找到更多信息here
答案 2 :(得分:-1)
private void btnSrcDataID_Click(object sender, EventArgs e)
{
try
{
dgvInsertInfo.Refresh();
SqlComm.Connection = SqlConn;
String sqlQueryString = ("SELECT * FROM MyDataTable WHERE
DataID=@DataID");
SqlComm.Parameters.AddWithValue("@DataID", txtDataID.Text);
SqlComm = new SqlCommand(sqlQueryString, SqlConn);
SqlDataTable = new DataTable();
SqlAdapt = new SqlDataAdapter(SqlComm);
DataSet dsQryDataId = new DataSet();
SqlAdapt.Fill(dsQryDataId);
//Passing data to DatagridView
dgvInsertInfo.DataSource = dsQryDataId;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
要
"INSERT INTO A (x, y, created_at)
(SELECT x, \"something\", a_timestamp
FROM B WHERE c IS NULL AND a_timestamp > \"#{current_time}\")