Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

如何在sqlite中关联两个表?

比如有note和tag两表:

CREATE TABLE note (
    note_id   TEXT PRIMARY KEY,
    note_text TEXT
);

CREATE TABLE tag (
    tag_id   TEXT PRIMARY KEY,
    tag_text TEXT
);

现在需要满足至少以下几个功能:

1)每个note可以有多个tag
2)每个tag可以关联多个note
总体上就像笔记应用中的标签功能,笔记可以设置标签,通过标签也可以搜索笔记。

这样的功能在一般的开发过程中怎样实现?如何写sql语句?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

note和tag多对多关系
加个note_tags表, 列是 note_id, tag_id
查询的时候通过 note_tags这个中间表做关联

demo

notes table

id    integer    NO    NULL    
note_text    text    YES    NULL    
created_at    datetime(6)    NO    NULL    
updated_at    datetime(6)    NO    NULL    

tags

id    integer    NO    NULL    
tag_text    varchar    YES    NULL    
created_at    datetime(6)    NO    NULL    
updated_at    datetime(6)    NO    NULL    

note_tags

id    integer    NO    NULL    
tag_id    integer    YES    NULL    
note_id    integer    YES    NULL    
created_at    datetime(6)    NO    NULL    
updated_at    datetime(6)    NO    NULL    

查询note id 是1的所有tags

SELECT "tags".* FROM "tags" INNER JOIN "note_tags" ON "tags"."id" = "note_tags"."tag_id" WHERE "note_tags"."note_id" = 1

查询tag id 是1的所有notes

SELECT "notes".* FROM "notes" INNER JOIN "note_tags" ON "notes"."id" = "note_tags"."note_id" WHERE "note_tags"."tag_id" = 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...