2016-04-25 34 views
1

在我的iOS和Android项目的单个查找,我有一个SQLite表看起来是这样的:更新文本列的内容与SQLite的

id words 
----------- 
1  apple, banana, orange, peach, strawberry 
2  car, plane, orange 
3  sheep, car, plane, horse, cow 
.  ... 
. 
. 

words列是一个TEXT列持有逗号分隔的单词列表。

我想通过在列表的前面添加一个单词来更新特定行的单词列表。该列表不应超过5个项目,因此如果有必要,我还会删除最后一个单词。

例如,如果要我更新row id 1cherry然后我会得到

cherry, apple, banana, orange, peach 

或者,如果我在做的row id 2相同的更新,然后我会得到

cherry, car, plane, orange 

我的问题

我知道我可以做aq uery获取行,处理文本,然后更新行。但是,这需要两个表查找,一个用于查询,另一个用于更新。这可能与单个更新查找有关吗?

我知道这里有replace() function但我没有在这里取代任何东西。我也不是简单的incrementing an integer。我在SQLite core functions中没有看到任何明显的东西。

回答

3

正确溶液

词语列是一个TEXT列保持逗号deliminated单词列表。

1 NF。 列包含原子数据。规范化模式以获得干净的代码和更好的性能。

解决方法解决:

SQLite不具有内置reverse功能,这就是为什么它是一个有点难看:

CREATE TABLE mytable(id INTEGER NOT NULL, words TEXT); 

INSERT INTO mytable(id,words) VALUES (1,'apple, banana, orange, peach, strawberry'); 
INSERT INTO mytable(id,words) VALUES (2,'car, plane, orange'); 
INSERT INTO mytable(id,words) VALUES (3,'sheep, car, plane, horse, cow'); 
INSERT INTO mytable(id,words) VALUES (4,'sheep, cherry, plane, horse, cow'); 

UPDATE mytable 
SET words = CASE 
      WHEN (LENGTH(words) - LENGTH(REPLACE(words, ',', ''))) < 4 
      THEN 'cherry, ' || words 
      ELSE SUBSTR('cherry, ' || words, 1, 
         LENGTH(words) + LENGTH('cherry, ') - 
         LENGTH(SUBSTR(SUBSTR(
         SUBSTR(SUBSTR(words, INSTR(words,',')+1), INSTR(SUBSTR(words, INSTR(words,',')+1), ',')+1), 
         INSTR(SUBSTR(SUBSTR(words, INSTR(words,',')+1), INSTR(SUBSTR(words, INSTR(words,',')+1), ',')+1), ',') + 1), 
         INSTR(SUBSTR(
         SUBSTR(SUBSTR(words, INSTR(words,',')+1), INSTR(SUBSTR(words, INSTR(words,',')+1), ',')+1), 
         INSTR(SUBSTR(SUBSTR(words, INSTR(words,',')+1), INSTR(SUBSTR(words, INSTR(words,',')+1), ',')+1), ',') + 1),',')+1)) -1 
        ) 
      END 
WHERE words NOT LIKE '%cherry%'; 

SELECT * FROM mytable; 

SqlFiddleDemo

为了使它更一般你需要用你的价值改变cherry

输出:

╔════╦══════════════════════════════════════╗ 
║ id ║    words     ║ 
╠════╬══════════════════════════════════════╣ 
║ 1 ║ cherry, apple, banana, orange, peach ║ 
║ 2 ║ cherry, car, plane, orange   ║ 
║ 3 ║ cherry, sheep, car, plane, horse  ║ 
║ 4 ║ sheep, cherry, plane, horse, cow  ║ 
╚════╩══════════════════════════════════════╝ 

它是如何工作的:

  • UPDATE ... WHERE words NOT LIKE '%cherry%';不更新有cherry已经
  • SET words = CASE WHEN (LENGTH(words) - LENGTH(REPLACE(words, ',', ''))) < 4如果定界符(逗号)的数量低于4只串联值的行字符串
  • 如果逗号的数量是4,表示它有5个值。在开始添加所需的字符串,然后用SUBSTRING从1到最后一个逗号

SQL Server版本比较:

DECLARE @val VARCHAR(100) = 'cherry'; 

UPDATE mytable 
SET words = CASE 
      WHEN LEN(words)-LEN(REPLACE(words, ',', '')) < 4 THEN @val + ', ' + words 
      ELSE LEFT(@val + ', ' + words, 
         LEN(@val + ', ' + words) - CHARINDEX(',', REVERSE(words))) 
      END 
WHERE words NOT LIKE '%'+ @val +'%'; 

SELECT * FROM mytable; 

LiveDemo

+1

哇,我印象深刻。我需要更多地研究如何规范化我的模式。 – Suragch