如何存储本质上是与 SQL 中的唯一值相关联的列表的数据

How to store data which is essentially a list tied to a unique value in SQL

这个问题可能已经被问了一千次了,但我不知道如何在 google 中表达它,所以我没有得到任何好的答案。

假设我在 SQL 中有一个 table "words",它在每一行的第一列中存储了一些单词。我想在这里做的是存储该词的所有同义词,并将它们 link 存储到第一列中的该词。例如,如果我有单词 "angry",我想将单词 "mad, bitter, enraged, furious, irritated" 等与该单词联系起来,所以如果我想通过 SQL 查询获取所有同义词,我可以轻松地这样做。

据我了解,尝试将列表存储在单元格中是行不通的。我唯一能想到的就是为 "angry" 的每个同义词都有一个行条目。但是如果一个词有很多同义词,或者我有很多词,感觉就会有很多条目(每个词都有很多不必要的重复)。有没有比这更好的做法来实现我的目标?

您使用两个 table,一个用于每个具有已定义外键关系的实体。 tables 看起来像:

create table words (
    WordId int not null primary key auto_increment,
    Word varchar(255)
    . . .
);

create table synonyms (
    SynonymId int not null primary key auto_increment,
    WordId int not null,
    Synonym varchar(255),
    . . .
    constraint fk_wordid foreign key (WordId) references Words(WordId)
);

如果同义词一定是单词,那么你会在第二个中使用id table:

create table synonyms (
    SynonymId int not null primary key auto_increment,
    WordId int not null,
    SynonymWordId int not null,
    . . .
    constraint fk_wordid foreign key (WordId) references Words(WordId),
    constraint fk_synonymwordid foreign key (SynonymWordId) references Words(WordId)
);

我也会使用两个表,但我的第二个表与 Gordon 的不同。

 table word
 wordID  int pk
 word varchar
 other fields

table synonym
wordID int FK to word
synonymID int FK to word
pk is both fields

angry的近义词查询

select s.word
from word w join synonym sy on w.wordID = sy.wordID
join word s on sy.synonymID = s.wordID
where w.word = 'angry'

A table 字词:

CREATE TABLE words (
  id integer PRIMARY KEY,
  word varchar(100) NOT NULL
);
INSERT INTO words VALUES (1,'angry'), (2,'mad'), (3,'bitter'),
(4,'enraged'), (5,'furious'), (6,'irritated'),
(7,'nice'), (8,'pleasant'), (9,'cute');

a table 同义词组

CREATE TABLE synonymgroups (
  id integer PRIMARY KEY,
  description varchar(100)
); 
INSERT INTO synonymgroups VALUES (1,'synonyms for "angry"'),
(2,'synonyms for "nice"');

和 table 组词映射

CREATE TABLE synonyms (
  synonymgroupid integer NOT NULL REFERENCES synonymgroups,
  wordid integer NOT NULL REFERENCES words,
  PRIMARY KEY (synonymgroupid,wordid)
); 
INSERT INTO synonyms(synonymgroupid,wordid) VALUES (1,1), (1,2), (1,3),
(1,4), (1,5), (1,6), (2,7), (2,8), (2,9);

查找单词 "mad" 的所有同义词:

SELECT s.wordid, w.word, s.synonymgroupid, sg.description
FROM synonyms s
  JOIN words w ON w.id=s.wordid
  JOIN synonymgroups sg ON sg.id=s.synonymgroupid
WHERE s.synonymgroupid IN (
  SELECT synonymgroupid
  FROM synonyms
  JOIN words ON words.id=synonyms.wordid
  WHERE words.word='mad'
);

PS。 SQL 数据库可能不是完成此类任务的最佳工具。这只是一个例子。