2015-12-11 155 views
0

我已经在我的MySQL数据库以下structur:嵌套INSERT INTO和SELECT语句

1表叫报告和1个表称为产品

我现在要插入基于选择的产品的报告。我得到的错误是以下几点:

错误代码:1242子查询返回多个1行0.000秒

我在去年的select语句(只选择,没有插入)我解决了这个错误与关键字“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行,对不对?

回答

0

你的问题是,当你尝试的

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' 
+0

我加了一些铁道部infomations! – Steinliiippp

+0

答案是一样的!您的SELECT语句返回多行,并且您尝试将多行插入到单个字段中,这不起作用。在最后的查询中,您选择了多个记录,但不要尝试将它们插入到任何位置,这就是它的工作原理。试试这个答案,看看它的回报。 – JCollerton

+0

好的,它的作品谢谢你。但是,请你解释一下如何使用insert并选择'UpdateMaster'?我怎样才能选择一个字符串? – Steinliiippp