将所有列中的唯一列选择为一列


Select unique from all columns into a single column

我设置了4列,它们基本上具有相同类型的数据。我想从所有列中的所有条目中的所有唯一条目创建另一个表。

    C1 (Name1)          C2 (name2)          C3 (name3)
R1  R1 C1 (John)        R1 C2 (Tiny Tim)    R1 C3 (Big Sally)
R2  R2 C1 (Big Sally)   R2 C2 (john)        R2 C3 (Paul)
R3  R3 C1 (Tiny Tim)    R3 C2 (paul)        R3 C3 (rajesh)
R4  R4 C1 (Normal Ned)  R4 C2 (Big Sally)   R4 C3 (Normal Ned)

这就是我需要的

    C1
R1  John
R2  Big Sally
R3  Tiny Tim
R4  Normal Ned
R5  Rajesh
R6  Paul

您可以使用UNION关键字来完成此操作。

SELECT c1 FROM table
UNION
SELECT c2 FROM table
UNION
SELECT c3 FROM table;

结果会如你所问。

然后只需获取值并将其插入到新表中,或者您可以使用插入。。。选择以快速插入。

请尝试以下操作:

   insert into newtablename
   (
        select distinct  uniquenames from (
            SELECT distinct c1 as uniquenames  FROM tablename
            UNION
            SELECT distinct  c2 as uniquenames  FROM tablename
            UNION
            SELECT distinct  c3 as uniquenames  FROM tablename)
    )

我能想到的最快的方法是:

CREATE TABLE c_unique (c1 varchar(100 not null));
ALTER TABLE c_unique ADD UNIQUE INDEX (c1);
INSERT IGNORE INTO c_unique(c1) SELECT c1 FROM table;
INSERT IGNORE INTO c_unique(c1) SELECT c2 FROM table;
INSERT IGNORE INTO c_unique(c1) SELECT c3 FROM table;

使用UNION将隐式地为您提供DISTINCT结果,并执行带有排序的临时操作来实现这一点。通过使用INSERTIGNORE,您只需在基于UNIQUE索引的INSERT操作中拒绝行,我认为这会更快。

注:对字符串列使用UNIQUE将适用于特定的字符长度。因此,您可能需要指定前缀长度。你可以在这里阅读更多关于这个主题的内容:CREATE INDEX语法