1

我有一个csv文件格式的同义词列表:word,meaning1,meaning2,meaning3....

不同的词有不同数量的同义词,这意味着行可能有可变数量的列。我正在尝试将 csv 文件导入到 sqlite 数据库中,如下所示:

    sqlite3 synonyms
    sqlite> create table list(word text, meaning0 text, meaning1 text, meaning2 text, meaning3 text, meaning4 text, meaning5 text, meaning6 text, meaning7 text, meaning8 text, meaning9 text);
sqlite> .mode list
sqlite> .separator ,
sqlite> .import ./csv/synonyms.csv list 

为了安全起见,我假设了一个最大值。每个单词的 10 列数。对于那些同义词少于 10 个的词,其他列应该是null。我在执行import命令时遇到的错误是:

Error: ./csv/synonyms.csv line 1: expected 11 columns of data but found 3  

我的问题:
1. 如果列数少于 10,我怎么知道SQLite用 代替它null
2. 有什么方法可以指定我想要单词后面的 10 列而不是自动输入?

4

1 回答 1

2

您可以执行以下操作:

  • 将所有数据导入单列;
  • 将表格拆分列内容更新为其他列。

样本:

-- Create a table with only one column;
CREATE TABLE table_name(first);
-- Choose a separator which doesn't exist within file
.separator ~
-- Import data
.import file.csv table_name

-- Add another column to split data
ALTER TABLE table_name ADD COLUMN second;
-- Split data between first and second column
UPDATE table_name SET first=SUBSTR(first, 1, INSTR(first, ",")-1), second=SUBSTR(first, INSTR(first, ",")+1) WHERE INSTR(first, ",")>0;

-- Repeat to next column
ALTER TABLE table_name ADD COLUMN third;
-- Split data between second and third column
UPDATE table_name SET second=SUBSTR(second, 1, INSTR(second, ",")-1), third=SUBSTR(second, INSTR(second, ",")+1) WHERE INSTR(second, ",")>0;

-- And so on...
ALTER TABLE table_name ADD COLUMN fourth;
UPDATE table_name SET third=SUBSTR(third, 1, INSTR(third, ",")-1), fourth=SUBSTR(third, INSTR(third, ",")+1) WHERE INSTR(third, ",")>0;

-- Many times as needed...

不是最佳方法,性能应该足够快。

于 2013-09-23T13:30:09.530 回答