如何一起选择帖子和共享帖子?

时间:2018-03-23 17:48:52

标签: mysql

我有一个系统,用户可以发布帖子并与其他朋友分享帖子,例如在Facebook上。

问题是我想一起从帖子和共享帖子中获取数据,我的意思是,顺序但帖子在桌面帖子和桌面共享帖子上分享:

CREATE TABLE IF NOT EXISTS `posts` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user` int(11) UNSIGNED NOT NULL,
  `titulo` text,
  `data` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `share` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user` int(11) UNSIGNED NOT NULL,
  `share_post_id` int(11) UNSIGNED NOT NULL,
  `data` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;

我有这个选择来获取帖子:

select c.nome, c.user, p.user, p.id, p.data, p.titulo, pp.foto, count(DISTINCT likes.user) as likes_count, count(distinct comentarios.id) as comentarios_count, count(DISTINCT l2.user) as count2 from posts p 
join cadastro c on p.user=c.id 
left join profile_picture pp on p.user = pp.user
left join likes on likes.post = p.id
left join comentarios on comentarios.foto = p.id and comentarios.delete = 0  
left join likes l2 on l2.post = p.id and l2.user = ?
group by p.id
order by p.id desc limit 20

如何与此选择中的帖子一起获得共享帖子?任何想法?

1 个答案:

答案 0 :(得分:1)

你可以通过简单地完成union all并将缺少的列添加为NULL来实现这一点!

     SELECT id,`user`,`data`,`titulo`,NULL as `share_post_id` from posts 
     union all 
     SELECT  id,`user`,`data`,NULL as `titulo`,`share_post_id` from `share`     order by id
相关问题