我的 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/