在sql中使用条件从3个不同的表中获取记录

z31licg0  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(340)

我在从数据库中获取特定类型的记录时遇到问题。
我有三张不同的table
朋友
追随者
图片库
这是这张table的样子

Friends:

|id | senderId | receiverId | accepted |   
|---|----------| -----------| ---------|   
| 1 | 1        | 12         | 1        |     
| 2 | 12       | 2          | 1        |  
| 2 | 12       | 2          | 1        |

Followers:

| id | userId | UserIsFollowing |  
| -- | ------ | --------------- |  
| 1  | 12     | 63              |  
| 2  | 22     | 12              |

PictureGalleries:

| id | UserId |   
| -- | ------ |  
| 1  | 13     |  
| 2  | 12     |  
| 3  | 1      |  
| 4  | 10     |  
| 5  | 2      |  
| 6  | 63     |

所以现在问题来了!
我想从图片库中全选
其中userid与userid 12有友谊关系,其中accepted为1
以及用户id 12跟随特定用户的位置
基本上,我想看到的结果是以下用户id的图片库:1、2和63,如下所示:

| id | UserID |
| -- | ------ |
| 3  | 1      |
| 5  | 2      |
| 6  | 6      |
9njqaruj

9njqaruj1#

我认为这个查询显示了您想要的:

select * from PictureGalleries
    join Followers on Followers.userId = PictureGalleries.UserId
    where exists (select 1 from Friends where (Friends.senderId = PictureGalleries.UserId or Friends.receiverId  = PictureGalleries.UserId) and accepted = 1)
    and Followers.UserIsFollowing  = :user_id

但我认为你的模式可以改进
编辑:
也许你先说错了当你说:
“其中userid与userid 12有友谊关系,其中accepted为1,并且userid 12跟随特定用户”
我想你的意思是,或者,sql应该是这样的:

select * from PictureGalleries
where exists (select 1 from Friends where (Friends.senderId = PictureGalleries.UserId or Friends.receiverId  = PictureGalleries.UserId) and accepted = 1)
OR exists (select 1 from Followers where Followers.userId = PictureGalleries.UserId and Followers.UserIsFollowing  = :user_id
tmb3ates

tmb3ates2#

使用union和sub查询获得所需的结果

select p.id,p.UserId from
   ( select UserIsFollowing as id from 
   Followers fl where userId =12 
   union select senderId from friends f 
   where f.receiverId =12 AND accepted=1 
   union select receiverId from friends f 
    where f.senderId =12 AND accepted=1 
   ) as t join PictureGalleries p on t.id=p.UserId

相关问题