如何在sqlite中链接两个表?

nqwrtyyt  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(730)

关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。

11个月前关门了。
改进这个问题
共有两个表:

  1. CREATE TABLE note (
  2. note_id TEXT PRIMARY KEY,
  3. note_text TEXT
  4. );
  5. CREATE TABLE tag (
  6. tag_id TEXT PRIMARY KEY,
  7. tag_text TEXT
  8. );

我想链接笔记和标签,就像一个笔记应用程序。
可以将标记设置为注解。此外,您还可以搜索带有标记的便笺。
如何编写sql?

kr98yfug

kr98yfug1#

你描述的是一种多对多的关系。这建议使用第三个表,它引用两个基表,并且每个关联存储在不同的行上:

  1. create table tag_notes (
  2. tag_id int references tags(tag_id),
  3. note_id int refereences notes(note_id),
  4. primary key (tag_id, note_id)
  5. )

注意,我使用了数据类型 int 对于外键列-这确实是您应该用于基表主键的内容。
使用此设置,您可以通过以下查询按文本搜索与给定标记相关的所有注解:

  1. select n.*
  2. from notes n
  3. inner join tag_notes tn on tn.note_id = n.note_id
  4. inner join tags t on t.tag_id = tn.tag_id
  5. where t.tag_text = 'mytag'

或者用一个 exists 条件:

  1. select n.*
  2. from notes n
  3. where exists (
  4. select 1
  5. from tag_notes tn
  6. inner join tags t on t.tag_id = tn.tag_id
  7. where t.tag_text = 'my tag' and tn.note_id = n.note_id
  8. )
展开查看全部

相关问题