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

时间:2018-09-12 16:35:24

标签: mysql database mysqli

所以我在从数据库中获取特定类型的记录时遇到问题。

我有三个不同的表

  1. 朋友
  2. 跟随者
  3. PictureGalleries

以下是表格的示例

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     | 

现在是问题所在!

我要从图片库中选择所有作品
其中,用户标识与用户标识12有友谊关系,其中接受为1
和 用户ID 12在关注特定用户的地方

因此,基本上我想看到的结果是以下用户ID的图片库:1,2和63,它们看起来像这样:

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

我只是希望我不会混淆你们。 谢谢!

2 个答案:

答案 0 :(得分:0)

我认为此查询显示了您想要的内容:

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

但是我认为您的模型可以改进

编辑:

也许您首先说错了:

“其中,如果用户标识与用户标识12有友谊关系,则接受的值为1 AND ,其中,用户ID 12跟随特定用户”

我认为您的意思是OR,因此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

答案 1 :(得分:0)

使用联合和子查询来获得所需的结果

   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