【问题标题】:insert multiple rows (one to many) based on other table根据其他表插入多行(一对多)
【发布时间】:2014-06-26 11:10:34
【问题描述】:

有两个表 Inspector(Parent) 和 InspectorOfficeAccess(Child),我需要让来自国家 (73,74) 的检查员访问办公室 (1,20,24,31,44)。

Inspector 表中有许多检查员(超过 100 名),国家为 73 和 74。是否可以通过一次查询将所有具有 officeid 的检查员插入 InspectorOfficeAccess 表中?

第二个屏幕截图用于显示最终结果的外观。 InspectorOfficeAcess 表为空。

每个检查员将插入 5 次 officeID (1,20,24,31,44) 其中检查员国家/地区 IN (73,74)

添加

到目前为止我已经尝试过了

insert into InspectorOfficeAccess 
select i.inspectorid,o.Offices    from Inspectors i
cross join 
        (
        SELECT 1 AS Offices
        UNION 
        SELECT 20
        UNION 
        SELECT 24
        UNION 
        SELECT 31
        UNION
        SELECT 44 
        ) o
where i.CountryID IN (73,74) 

【问题讨论】:

  • 是的,这是可能的。到目前为止,您尝试了什么?
  • 可以使用 officeID(1,20,24,31,44) 跨越国家 (73,74) 的所有检查员,并在插入语句中使用它......

标签: sql sql-server-2008


【解决方案1】:

如果您必须从其他表中选择 Office Id,那么另一种方法是:

Insert into InspectorOfficeAccess
Select I.InspectorID,O.OfficeId
from  Inspector I 
Cross Join Office O
where I.CountryId in (73,74) and O.OfficeId in (1,20,24,31,44);

您可以查看Demo here.

【讨论】:

  • 非常干净的例子:)
【解决方案2】:

试试这个

Insert into InspectorOfficeAcess
Select InspectorOfficeAccessiD,i.InspectorID,oficeid
from  Inspector i 
cross apply(Select 1 union Select 20 union Select 24 union Select 31 union Select 44) d
    where countryid in (73,74)

【讨论】:

  • 第二个屏幕截图用于显示最终结果的外观。 InspectorOfficeAcess 表为空。
  • 第二个屏幕截图显示了三列; InspectorOfficeAccessiD、i.InspectorID、oficeid InspectorOfficeAccessiD 是 IDENTITY 列,因此需要 i.InspectorID、oficeid。
  • 每个检查员将插入 5 次 officeID (1,20,24,31,44) 其中检查员国家/地区 IN (73,74)
  • 不要担心 InspectorOfficeAccessiD 作为它的标识列
【解决方案3】:

这适用于您的情况:

SELECT *
FROM (SELECT InspectorID
      FROM Inspector
      WHERE countryid in (73,74)) Inspector
,(VALUES (1),(20),(24),(31),(44)) 
AS InspectorOfficeAcess(InspectorOfficeAcessID)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    相关资源
    最近更新 更多