我要用sql查询出来,我所发布的帖子和我关注的用户发布的帖子,这个sql该怎么写啊?

select t.*
from talk t
where t.user_id = 2
Union
select t.*
from talk t, user_contact c
where c.user_id = 2 and c.contact_type = 1 and c.be_user_id = t.user_id

这么写可以但是不想这么写 ,想用 内连接或者左连接

存在一种情况就是这个user在user_contact 表里面没数据,代表他没关注任何人

user_id = 1 是用户的id,也就是我的id

select t.*
from talk t left join user_contact c on c.user_id = t.user_id
where t.user_id = 1 or (c.user_id = 1 and c.be_user_id = t.user_id and c.contact_type = 1)

搞不明白哪里有错啊,为啥就会有重复数据呢

我这样写查询出来有重复数据

user_contact是用户关系表

talk 是帖子表

帖子表talk有存发布帖子的用户的user_id
然后用户关系表user_contact 存了 user_id,be_user_id是被关注的用户的id,contact_typ_type是用户关系类型,1为关注类型

求教,不知道该怎么写了

阅读 2.3k
2 个回答
select * from talk 
where user_id=1 
or user_id in (
select be_user_id from user_contact where user_id=1 and contact_type = 1
)

talk跟user_contact是多对多的关系!!!
举个栗子:user_id = 1发布了m篇帖子,并且他关注了n个人,那么你写的那句left join至少会出现m*n条记录,采用的是笛卡尔积,实际上你只需要m条而已,加个group by即可。

select t.*
from talk t left join user_contact c on c.user_id = t.user_id
where t.user_id = 1 or (c.user_id = 1 and c.be_user_id = t.user_id and c.contact_type = 1)
group by t.user_id

但是,当你再看上面的left join条件和where后面的or条件,会发现c.user_id = t.user_id = 1 !!!什么意思,就是关联出来的结果还是显示用户1的帖子,并不会把他关注的人的帖子关联出来。
正确的应该是:

select t.*
 from talk t , user_contact c
 where t.user_id = 1 or (c.user_id = 1 and c.be_user_id = t.user_id and c.contact_type = 1)
 group by t.user_id

这是按你写的来改造的,论效率楼上那样写比较好

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题