c++ - sql Column with multiple values(cpp文件中的查询实现)

标签 c++ mysql sql sql-server eclipse

我正在使用 this链接。

我已经将我的 cpp 文件与 Eclipse 连接到我的数据库,其中包含 3 个表(两个简单的表 PersonItem 第三个 PersonItem 连接它们)。在第三张表中,我使用了一个简单的主键,然后使用了两个外键:

CREATE TABLE PersonsItems(PersonsItemsId int not null auto_increment primary key,
Person_Id int not null,
Item_id int not null,
constraint fk_Person_id foreign key (Person_Id) references Person(PersonId),
constraint fk_Item_id  foreign key (Item_id) references Items(ItemId));

所以,然后在 c 中使用嵌入式 sql,我希望一个人有多个项目。

我的代码:

   mysql_query(connection, \
   "INSERT INTO PersonsItems(PersonsItemsId, Person_Id, Item_id) VALUES (1,1,5), (1,1,8);");

    printf("%ld PersonsItems Row(s) Updated!\n", (long) mysql_affected_rows(connection));

   //SELECT newly inserted record.
   mysql_query(connection, \
   "SELECT Order_id FROM PersonsItems");

   //Resource struct with rows of returned data.
   resource = mysql_use_result(connection);

   // Fetch multiple results
   while((result = mysql_fetch_row(resource))) {
       printf("%s %s\n",result[0], result[1]);
   }

我的结果是

-1 PersonsItems Row(s) Updated!
5

但使用 VALUES (1,1,5), (1,1,8);

我愿意这样

-1 PersonsItems Row(s) Updated!
5 8

有人能告诉我为什么这没有发生吗? 亲切的问候。

最佳答案

我怀疑这是因为您的第一次插入失败并出现以下错误:

Duplicate entry '1' for key 'PRIMARY'

因为你试图将 1 插入到 PersonsItemsId 中两次,它是主键所以必须是唯一的(它也是 auto_increment 所以不需要指定一个值);

这就是受影响的行数为 -1 的原因,以及为什么在这一行中:

printf("%s %s\n",result[0], result[1]);

你只看到 5 因为第一条语句在值 (1,1,5) 已经被插入之后失败了,所以仍然有一行数据在表中。

我认为要获得您期望的行为,您需要使用 ON DUPLICATE KEY UPDATE语法:

INSERT INTO PersonsItems(PersonsItemsId, Person_Id, order_id) 
VALUES (1,1,5), (1,1,8)
ON DUPLICATE KEY UPDATE Person_id = VALUES(person_Id), Order_ID = VALUES(Order_ID);

Example on SQL Fiddle

或者不指定 personsItemsID 的值,让 auto_increment 做它的事情:

INSERT INTO PersonsItems( Person_Id, order_id) 
VALUES (1,5), (1,8);

Example on SQL Fiddle

关于c++ - sql Column with multiple values(cpp文件中的查询实现),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19138213/

相关文章:

MySql - 选择 MAX 和 MIN 并返回相应的行

sql - 如何在 Postgres 中启用对一个模式和公共(public)模式的访问

mysql - SQL 获取最大日期

c++ - 有效地使用带数组的 KMP 来计算词频计数

c++ - 为什么 std::unordered_set 重新散列,即使负载因子限制没有被打破?

python - 检查数据库中新条目的最快和最有效的方法是什么?

mysql根据条件计算成列

c++ - 有没有更好的方法在 C++ 中改组 vector ?

c++ - 如何在 C++ 中定义一个 const 指针数组?

mysql - SQL Server 自动递增下一个 INSERT 查询