如何在 Sqlite 中 link 两个表?
How to link two tables in Sqlite?
有 2 个表:
CREATE TABLE note (
note_id TEXT PRIMARY KEY,
note_text TEXT
);
CREATE TABLE tag (
tag_id TEXT PRIMARY KEY,
tag_text TEXT
);
我想link做笔记和标签,就像一个笔记应用程序。
您可以为笔记设置标签。另外,您可以搜索带标签的笔记。
SQL怎么写?
您描述的是多对多关系。这表明第三个 table,它引用两个基 tables,并且每个关联存储在不同的行中:
create table tag_notes (
tag_id int references tags(tag_id),
note_id int refereences notes(note_id),
primary key (tag_id, note_id)
)
请注意,我对外键列使用了数据类型 int
- 这确实是您应该对基本 tables.
的主键使用的数据类型
有了这个设置,您可以使用以下查询按文本搜索与给定标签相关的所有笔记:
select n.*
from notes n
inner join tag_notes tn on tn.note_id = n.note_id
inner join tags t on t.tag_id = tn.tag_id
where t.tag_text = 'mytag'
或具有 exists
条件:
select n.*
from notes n
where exists (
select 1
from tag_notes tn
inner join tags t on t.tag_id = tn.tag_id
where t.tag_text = 'my tag' and tn.note_id = n.note_id
)
有 2 个表:
CREATE TABLE note (
note_id TEXT PRIMARY KEY,
note_text TEXT
);
CREATE TABLE tag (
tag_id TEXT PRIMARY KEY,
tag_text TEXT
);
我想link做笔记和标签,就像一个笔记应用程序。
您可以为笔记设置标签。另外,您可以搜索带标签的笔记。
SQL怎么写?
您描述的是多对多关系。这表明第三个 table,它引用两个基 tables,并且每个关联存储在不同的行中:
create table tag_notes (
tag_id int references tags(tag_id),
note_id int refereences notes(note_id),
primary key (tag_id, note_id)
)
请注意,我对外键列使用了数据类型 int
- 这确实是您应该对基本 tables.
有了这个设置,您可以使用以下查询按文本搜索与给定标签相关的所有笔记:
select n.*
from notes n
inner join tag_notes tn on tn.note_id = n.note_id
inner join tags t on t.tag_id = tn.tag_id
where t.tag_text = 'mytag'
或具有 exists
条件:
select n.*
from notes n
where exists (
select 1
from tag_notes tn
inner join tags t on t.tag_id = tn.tag_id
where t.tag_text = 'my tag' and tn.note_id = n.note_id
)