【问题标题】:Nested Insert into and select statement嵌套插入和选择语句
【发布时间】:2015-12-11 11:38:55
【问题描述】:

我的 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 行,对吧?

【问题讨论】:

    标签: mysql


    【解决方案1】:

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

    的结果时
    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'
    

    【讨论】:

    • 我添加了一些铁道信息!
    • 答案是一样的!您的 SELECT 语句返回多行,并且您尝试将多行插入到单个字段中,但这是行不通的。在最终查询中,您选择了几条记录,但不要尝试将它们插入任何地方,这就是它起作用的原因。试试这个答案,看看它会返回什么。
    • 好的,是的,谢谢。但是您能否解释一下如何使用插入并选择“UpdateMaster”?如何选择字符串?
    • 对于字符串,它将为查询返回的每一行选择字符串。对于 SELECT INTO,我会查看文档和教程,我不会那么擅长解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2017-09-15
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多