同一个表中列的SQL Update ID

时间:2015-12-30 21:21:02

标签: sql sql-server

我确信这在其他地方得到了解答,但我不确定如何搜索这个具体问题。

假设我有两张桌子:

  • InputDataNames[Prospect_Name], [Product_Name], [Market_Name]

  • Entity[EntityId], [Name], [EntityTypeId],其中[Name]表格中使用了InputDataNames

现在假设我要创建一个等于InputDataNames的表,但不是名字,而是填写Entity表中的ID:

  • InputDataIDs[Prospect_ID], [Product_ID], [Market_ID]

使用InputDataNames表填充适当的ID组合,如何与Entity表联接以获得所需的效果?

注意:我知道这很草率,只是做了一点数据库清理。

2 个答案:

答案 0 :(得分:0)

insert  InputDataIDs
        (Prospect_ID, Product_ID, Market_ID)
select  Prospect.EntityID
,       Product.EntityID
,       Market.EntityID
from    InputDataNames
left join
        Entity Prospect
on      Prospect.EntityTypeId = 1 -- Type of prospect
        and Prospect.Name = InputDataNames.Prospect_Name
left join
        Entity Product
on      Product.EntityTypeId = 2 -- Type of product
        and Product.Name = InputDataNames.Product_Name
left join
        Entity Market
on      Market.EntityTypeId = 3 -- Type of market
        and Market.Name = InputDataNames.Market_Name

答案 1 :(得分:0)

您可以三次加入实体表。假设EntityTypeId列确定实体是潜在客户,产品还是市场,那么您应该在联接中包含该列。如果它们编号为1,2,3:

select 
    pros.entityid, prod.entityid, mkt.entityid
from 
    inputdatanames id
inner join 
    entity pros on id.prospect_name = pros.name and pros.entitytypeid = 1
inner join 
    entity prod on id.product_name = prod.name and prod.entitytypeid = 2
inner join 
    entity mkt on id.market_name = mkt.name and mkt.entitytypeid = 3