3

假设我有一个这样的 SQL 表:

UniqueID  Word
1         apple
2         orange
3         banana
4         apple

我想将哈希键创建为整数。该整数应该映射到特定的单词。为了使键具有某种意义,我希望该数字是单词第一次出现的 UniqueID。这意味着我想生成这样的表:

Unique ID  Word    WordHash
1          apple   1
2          orange  2
3          banana  3
4          apple   1

我尝试使用 group by 语句以及 min(unique id),但这摆脱了最后一个苹果行。我想保留那一排。

4

3 回答 3

1
SELECT t.UniqueID, t.Word, q.MinID AS WordHash
    FROM YourTable t
        INNER JOIN (SELECT Word, MIN(UniqueID) AS MinID
                        FROM YourTable
                        GROUP BY Word) q
            ON t.Word = q.Word
于 2012-09-27T21:36:59.700 回答
1

如果您想在原始表中创建新列,而不仅仅是获取结果集:

update 
    t 
    inner join (
        select Word, min(UniqueID) as id
        from t
        group by Word
    ) s on t.Word = s.Word    
set t.WordHash = s.id
于 2012-09-27T21:46:46.250 回答
1

您需要执行以下查询

ALTER TABLE <table_name> ADD COLUMN `WordHash` INT NULL AFTER `Word`;

UPDATE <table_name> t INNER JOIN 
    (SELECT `word`, MIN(uniqueId) AS MinID FROM <table_name> GROUP BY `word`) q 
     ON t.word = q.word 
     SET WordHash = q.MinID;

希望能帮助到你...

于 2012-09-27T21:55:22.517 回答