使用SubQuery MySQL插入 [英] INSERT INTO with SubQuery MySQL

查看:76
本文介绍了使用SubQuery MySQL插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这句话:

INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
    VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));

我正在尝试插入一个值,该值复制了item_costprice的相同数据,但显示了错误:

I'm trying to insert a value copy the same data of item_costprice, but show me the error:

Error Code: 1136. Column count doesn't match value count at row 1

我该如何解决?

推荐答案

SELECT语句中使用带有别名的数字文字. SELECT组件周围不需要().

Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.

INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
  SELECT
    /* Literal number values with column aliases */
    1 AS item_code,
    2 AS invoice_code,
    item_costprice
  FROM qa_items 
  WHERE item_code = 1;

请注意,在INSERT INTO...SELECT的上下文中,别名实际上并不是必需的,您可以只是SELECT 1, 2, item_costprice,但是在普通的SELECT中,您将需要别名来访问返回的列.

Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.

这篇关于使用SubQuery MySQL插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆