如何插入具有返回多个值的子查询的数据?

huangapple go评论58阅读模式
英文:

how to insert data with subquery that returns more than on value?

问题

我有两个表格,company_listcompany_detailscompany_list 表格有一个 company_id 列,而 company_details 表格包含与 company_id 相关的一些公司信息。我想要将数据插入到 company_details 表格中,但是只包括在 company_details 表格中没有的 company_id

我尝试使用以下查询,但是出现了错误。

INSERT INTO company_details (company_id, detail_found)
VALUES ((SELECT company_id FROM company_list WHERE company_id NOT IN (SELECT company_id FROM company_details)), '未找到数据');

错误信息为:

Msg 512, Level 16, State 1, Line 27

子查询返回多个值。当子查询跟随 =、!=、<、<=、>、>= 等运算符时,或者当子查询用作表达式时,不允许出现这种情况。

语句已终止。

如何使用返回多个值的子查询插入数据到表格中?

英文:

I have two tables company_list and company_details. The company_list table has a company_id column, and the company_details has some information related to the company with the company_id. I wanted to insert data into the company_details table with the company_id not in the company_details table.
I tried it with the following query but it gave me an error.

INSERT INTO company_details (company_id,detail_found)
VALUES ((SELECT company_id FROM company_list WHERE company_id  NOT IN (SELECT company_id FROM company_details)), &#39;No data found&#39;);

The error is:

> Msg 512, Level 16, State 1, Line 27
>
> Subquery returned more than 1 value. This is not permitted when the
> subquery follows =, !=, <, <= , >, >= or when the subquery is used as
> an expression.
>
> The statement has been terminated.

How to insert data into the table with a subquery that returns more than one value?

答案1

得分: 2

你可以使用一个插入选择语句(不包括 values 子句),并将字符串字面值查询为选择语句的一列:

INSERT INTO company_details (company_id, detail_found)
SELECT company_id, '未找到数据'
FROM   company_list
WHERE  company_id NOT IN (SELECT company_id FROM company_details)
英文:

You can use an insert-select statement (without the values clause), and query the string literal as one of the select's columns:

INSERT INTO company_details (company_id,detail_found)
SELECT company_id, &#39;No data found&#39; 
FROM   company_list 
WHERE  company_id NOT IN (SELECT company_id FROM company_details)

huangapple
  • 本文由 发表于 2023年1月9日 16:39:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定