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"]
  }
]
阅读 3.8k
1 个回答
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
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题