mysql主表关联多个子表问题
本文介绍了mysql主表关联多个子表问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
目前在处理一个类似于发帖子的功能。
表设计如下:
meta表(存储元信息)
id(帖子ID) | type(帖子类型) | recommend(推荐帖子) | created_at(发表时间) | user_id(用户ID) |
---|---|---|---|---|
1 | 1 | 0 | 1499831287 | 1 |
2 | 2 | 0 | 1499831287 | 1 |
text表(存储type为1纯文本帖子
的帖子数据):
id | text |
---|---|
1 | test01 |
media表(存储type为2图文帖子
的帖子数据):
id | text | images |
---|---|---|
2 | test02 | ["https://www.baidu.com/img/logo.gif"] |
想要实现的效果是返回以下结构的数据:
[
{
"id": 1,
"type": 1,
"recommend": 0,
"created_at": 1499831287,
"user_id": 1,
"text": "test01"
},
{
"id": 2,
"type": 2,
"recommend": 0,
"created_at": 1499831287,
"user_id": 1,
"text": "test02",
"images": ["https://www.baidu.com/img/logo.gif"]
}
]
解决方案
select t1.*,t2.text,null as images
from meta t1
left join text t2 on t1.id=t2.id and t1.type=1
union all
select t1.*,t2.text,t2.images
from meta t1
left join text t2 on t1.id=t2.id and t1.type=2
这篇关于mysql主表关联多个子表问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文