gpt4 book ai didi

sql - MySQL 多表连接 ID

转载 作者:行者123 更新时间:2023-11-29 14:54:30 25 4
gpt4 key购买 nike

嘿,我需要一些关于 MYSQL 连接的帮助,我真的不知道如何实现,或者 MySQL 是否允许。

我有一些表设置,post_controller、post_text、post_photo、post_link。

post_controller 拥有所有 ID,并且 post_text、post_photo、post_link 表不能有条目,除非 post_controller 有 id 条目(外键)。我之所以采用这种方法,是因为我有不同类型的帖子,并且无论帖子类型如何,我都想检索它们,所以我只使用主表中的 ID。

我想知道的是,如何将 3 个表与主表连接起来形成一个包含所有帖子的大数组,假设我想要帖子 1 到 20 ..我可以加入每种类型吗每个表中的帖子就像这样。

post_contoller

id userid type time
1 2 1 00:00
2 4 1 00:00
3 5 2 00:00
4 23 2 00:00
5 8 3 00:00
post_text

id content title
1 {sometext} {sometext}
2 {sometext} {sometext}
post_photo

id content hash
3 {sometext} {somehash}
4 {sometext} {somehash}
post_link

id content desc link
5 {sometext} {sometext} {somelink}

最终结果数据集。

post_photo

id userid type time content title desc link hash
1 2 1 00:00 {sometext} {sometext}
2 4 1 00:00 {sometext} {sometext}
3 5 2 00:00 {sometext}
4 23 2 00:00 {sometext} {somehash}
5 8 3 00:00 {sometext}{somelink}

通过根据 post_controller 中的主 ID 连接 3 个表是否可以得到此结果集。如果是,请解释,如果否,请尽可能提出替代解决方案。

谢谢。

最佳答案

是的,这是可能的:

   SELECT c.*,
IFNULL(IFNULL(p.content, t.content), l.content) AS content,
t.title,
l.desc,
l.link,
p.hash
FROM post_contoller c
LEFT JOIN post_text t ON t.id = c.id
LEFT JOIN post_photo p ON p.id = c.id
LEFT JOIN post_link l ON l.id = c.id

关于sql - MySQL 多表连接 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4976002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com