gpt4 book ai didi

mysql - SQL 从另一个表中获取数据

转载 作者:行者123 更新时间:2023-11-29 03:17:22 25 4
gpt4 key购买 nike

我有以下类型的表

1. feeds ( id, user_id, type, object_id)
2. badge ( id, 'badge_name', 'slug' )
3. Post (id, 'post_name', 'post_type')

我想根据提要类型从提要表中获取所有用户提要,如果提要类型是 badge,则 object_id 将引用“badge”表,如果提要类型是 blog,则 object_id 将引用“Post”表在单个查询中。

实现此目标的最佳方法是什么?

目前我正在通过代码来做这件事并且也在工作。只是想增强它。

最佳答案

使用左连接和合并函数

select f.*,coalesce(b.badge_name,p.post_name),
coalesce(b.slug,p.post_type)
from feeds f
left join badge b on f.object_id=b.id
left join post p on f.object_id=p.id

关于mysql - SQL 从另一个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53040264/

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