mysql - 嵌套 Insert into 和 select 语句

标签 mysql

我的 MySql 数据库中有以下结构:

1 个名为报告的表和 1 个名为产品的表

我现在想根据选择的产品插入到报告中。我得到的错误如下:

错误代码:1242。子查询返回超过 1 行 0.000 秒

在我的最后一个选择语句(仅选择,不插入)中,我使用关键字“IN”解决了此错误,但在这种情况下它不起作用。这是我到目前为止的查询(产生错误)

INSERT INTO reports (report_date, report_emploee, report_content, report_art, report_adressnummer)
VALUES(
NOW(), 
'UpdateMaster', 
'content', 
'AutoUpdate' , 
(SELECT product.product_adressnummer 
FROM product 
WHERE product.product_name='testproduct'
AND product.product_version='2.50c' 
AND product_updateDatum >= '2015-12-11'));

我尝试使用 select 语句创建一个数组,然后在插入报告期间对其进行迭代,但我没有在 sql 中得到它。网上的所有信息都结合了sql和php来使其工作。

如果我执行查询,它将如下所示:

report_date=today
report_emploee='UpdateMaster'
report_content='content'
report_art='AutoUpdate'
report_adressnummer=123,456,789,310,...

但它应该像这样执行:

report_date=today
report_emploee='UpdateMaster'
report_content='content'
report_art='AutoUpdate'
report_adressnummer=123

report_date=today
report_emploee='UpdateMaster'
report_content='content'
report_art='AutoUpdate'
report_adressnummer=456

report_date=today
report_emploee='UpdateMaster'
report_content='content'
report_art='AutoUpdate'
report_adressnummer=789

......

您的解决方案影响了 sql 表中的 0 行。

如果我执行此查询:

SELECT contact.contact_vorname, contact.contact_nachname, contact.contact_eMail
FROM contact 
WHERE contact.contact_adressnummer IN
(SELECT product.product_adressnummer 
FROM product 
WHERE product.product_name='toolstar®TestLX'
AND product.product_version='2.50c' 
AND product_updateDatum >= '2015-12-11');

它返回 8 行,您的解决方案也应该影响 8 行,对吗?

最佳答案

您遇到的问题是当您尝试插入

的结果时
SELECT product.product_adressnummer 
FROM product 
WHERE product.product_name='testproduct'
AND product.product_version='2.50c' 
AND product_updateDatum >= '2015-12-11'

进入你的表。由于这会返回多条记录,因此您无法将其插入一条记录应在的位置。 IN 无法解决问题,因为这不会阻止返回多个记录。

如果您想为返回的每条记录插入一条记录,您可以使用:

INSERT INTO 
    reports (report_date, report_emploee, report_content, report_art, report_adressnummer)
SELECT
    NOW(), 
    'UpdateMaster', 
    'content', 
    'AutoUpdate' ,
    product.product_adressnummer 
FROM product 
WHERE product.product_name='testproduct'
AND product.product_version='2.50c' 
AND product_updateDatum >= '2015-12-11'

关于mysql - 嵌套 Insert into 和 select 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34222714/

相关文章:

mysql - 实现条件mysql where子句的最佳方法

过去 12 个月的 MySQL 月度销售额,包括没有销售额的月份

从控制台调用时 MySQL 请求返​​回结果,但使用 ActiveRecord 请求时为空

使用 AND 和 OR 的 mysql 查询 where 子句

mysql - 重叠的时间间隔

MySQL 计数与二进制字段的连接

php - 在文本区域输入的数据不会进入使用 php 和 mysqli 设计的数据库

MySQL正则表达式转义$

php - 我的选择菜单每次显示每个记录的每个端口(伦敦、利物浦、都柏林),我只想要每个端口一次

php - MySQL查询结果的第一行未显示