正确溶液
词语列是一个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
哇,我印象深刻。我需要更多地研究如何规范化我的模式。 – Suragch