2016-03-15 35 views
0

所以我们说你继承了只有一个表像这样的SQLITE3数据库:SQLITE3去除冗余,多余的参考表

CREATE TABLE data (id integer, name text) 

它看起来像这样:

------- DATA ------- 
89074352 red 
12344112 red 
47298489 blue 
34444333 blue 
23453245 red 
10000001 yellow 
... 
-------------------- 

所以文本元素并且非常多余。并设想文本元素是巨大的,而不是一个字。你可能想要通过只包含一次文本元素的新表来避免这种情况。数据库的最终状态将有看起来像这样的两个表:

CREATE TABLE text_keys ("key" integer primary key autoincrement, "name" text not null) 
------- TEXT_KEYS ------- 
1 red 
2 blue 
3 yellow 
... 
------------------------- 

CREATE TABLE data ("id" integer, "key" integer references text_keys) 
------- DATA ------- 
89074352 1 
12344112 1 
47298489 2 
34444333 2 
23453245 1 
10000001 3 
... 
-------------------- 

什么命令会在你键入SQLITE3从第一状态进入到数据库的最终状态?我做了一些研究,但还没有能够解决这个问题。

回答

1

首先创建参考表,然后创建新的数据表。它会像这样:

create table text_keys (
     text_key_id integer primary key, 
     name text 
    ); 

    insert into text_keys (text_key_id, name) 
     select distinct NULL, name 
     from data; 

create table new_data as 
    select d.id, tk.text_key_id 
    from data d join 
     text_keys tk 
     on d.name = tk.name;