如何在 sqlite3 中正确连接这些表
how to join these tables properly in sqlite3
我有 3 个 table。首先是 Posts tables 看起来像这样
id
post_creator
1
Mark
2
John
3
David
4
Ellie
5
Thomas
6
Elliot
有两种 post。图片 post 和文字 post。我有 2 个不同的 table 给他们。这是 text_posts table 的样子:
post_id
post_text
1
lorem ipsum
4
lorem ipsum
5
lorem ipsum
同样有一个 image_posts table 都遵循来自 posts table
的 id
post_id
post_text
post_image
2
lorem ipsum
image_url
3
lorem ipsum
image_url
6
lorem ipsum
image_url
现在我不关心 post_image url,我只想从 Post table 获得 post_creator 以及 post 是否在 text_post table 或 image_post table 我想要文本。我该怎么做?
我假设您使用的是 SQL Db。
在这种情况下,Posts 和 post_text/image_posts 是 NtoN 关系,因此您应该将关系标准化为 2 1toN。
在这种情况下,它以 1 table Post、2 Table: Post_text 和 Post_img 以及另一个维护“历史”的 table 结尾post 每个用户。
您应该创建另一个名为 Creates(id, user_id, post_id).
的 table
然后可以加入2个table得到post_creator.
SELECT
post_id, post_text, post_image
FROM Posts
LEFT JOIN text_posts ON text_posts.post_id = Posts.id
LEFT JOIN image_posts ON image_posts.post_id = Posts.id
然后你会得到一个table,结果是table的所有字段。要了解 post 是否是图像,只需检查 post_image 字段即可。如果它是 != null 那么它将是 image_post.
但是,你用的结构很糟糕,我建议你更好地研究一下如何构建SQL table和Db,并尝试以更好的方式重新构建你的数据方式,遵循规范化规则。
我有 3 个 table。首先是 Posts tables 看起来像这样
id | post_creator |
---|---|
1 | Mark |
2 | John |
3 | David |
4 | Ellie |
5 | Thomas |
6 | Elliot |
有两种 post。图片 post 和文字 post。我有 2 个不同的 table 给他们。这是 text_posts table 的样子:
post_id | post_text |
---|---|
1 | lorem ipsum |
4 | lorem ipsum |
5 | lorem ipsum |
同样有一个 image_posts table 都遵循来自 posts table
的 idpost_id | post_text | post_image |
---|---|---|
2 | lorem ipsum | image_url |
3 | lorem ipsum | image_url |
6 | lorem ipsum | image_url |
现在我不关心 post_image url,我只想从 Post table 获得 post_creator 以及 post 是否在 text_post table 或 image_post table 我想要文本。我该怎么做?
我假设您使用的是 SQL Db。
在这种情况下,Posts 和 post_text/image_posts 是 NtoN 关系,因此您应该将关系标准化为 2 1toN。 在这种情况下,它以 1 table Post、2 Table: Post_text 和 Post_img 以及另一个维护“历史”的 table 结尾post 每个用户。 您应该创建另一个名为 Creates(id, user_id, post_id).
的 table然后可以加入2个table得到post_creator.
SELECT
post_id, post_text, post_image
FROM Posts
LEFT JOIN text_posts ON text_posts.post_id = Posts.id
LEFT JOIN image_posts ON image_posts.post_id = Posts.id
然后你会得到一个table,结果是table的所有字段。要了解 post 是否是图像,只需检查 post_image 字段即可。如果它是 != null 那么它将是 image_post.
但是,你用的结构很糟糕,我建议你更好地研究一下如何构建SQL table和Db,并尝试以更好的方式重新构建你的数据方式,遵循规范化规则。