【问题标题】:Generate connection table from table with duplicates从具有重复项的表生成连接表
【发布时间】:2012-06-05 18:49:03
【问题描述】:

我有一个 SQL Server 数据库表 (DuplicateIds),其中包含另一个表 (Words) 中重复单词的 ID。以下是 DuplicateIds 表中的数据示例:

        word_id  |  word
----------------------------------
        244      |  ape
        603      |  ape
       1873      |  ape
        372      |  banana
       3095      |  banana

...等等。通常只有两三个重复,但也有 10 个甚至更多重复的情况。

现在我想使用这个带有重复项的表来创建一个新表,该表将相同单词的 ID 连接起来。我猜新表看起来像这样:

        word_id  |  connected_id
----------------------------------
        244      |    603
        244      |   1873
        603      |    244
        603      |   1873
       1873      |    244
       1873      |    603
        372      |   3095
       3095      |    372

通过这个表,我可以使用它的 ID 查找某个单词,并获取所有相同单词的 ID。

现在我想知道是否可以使用来自 DuplicateIds 的数据编写一个 (T)SQL 语句来为我生成这个新的连接表?

【问题讨论】:

    标签: sql sql-server duplicate-data auto-generate database-table


    【解决方案1】:

    应该这样做:

    SELECT
       di.word_id
      ,di2.word_id  connected_id
     into NewTable
     from DuplicateIds di
      inner join DuplicateIds di2
       on di2.word = di.word
        and di2.word_id <> di.word_id
    

    【讨论】:

    • 嗨!此解决方案是否要求我首先复制表 DuplicateIds(我指的是您的示例中的 di2 表)?
    • 没关系 - 我刚刚看到那些别名。它似乎工作得很好——创建了一个包含 2534 条新记录的表!
    【解决方案2】:

    试试这个。我不确定在 sql server 中如何不相等。

     INSERT INTO DuplicateIds 
     SELECT a.word_id, b.word_id  connected_id
     from Words a,Words b
     where a.word=b.word
     and a.word_id <> b.word_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 2018-07-15
      • 2018-02-20
      • 1970-01-01
      • 2020-07-13
      • 2018-05-07
      • 2022-09-23
      相关资源
      最近更新 更多