使用mysql在一个查询中连接三个表

xlpyo6sf  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(370)

我的表名为


**Subscription Table**

-------------------------------
id    actors_id      user_id
-------------------------------
1       5               1
2       7               2
3       12              96
4       18              54

**Actors Content**

-------------------------------
id    contend_id       actors_id
-------------------------------
1      25               5
2      65               18
3      120              18
4      98               12

**Content Table**

-------------------------------
r_id     title       content_post
-------------------------------
25     abvg         xxxxxxxxx
65     djki         fffffffff
98     sdrt         rrrrrrrrr
120    fgty         tttttttty

所以我首先需要从订阅表中获取actors\u id,因为我知道user\u id的值,然后需要从actors内容表中获取content\u id,最后从content表中获取r\u id并在站点上显示。
我试过一些东西,但这绝对不好

SELECT Content.*, (SELECT Actors.contend_id FROM Actors WHERE Actors.contend_id = Content.r_id) as views FROM Content,Actors WHERE Actors.actors_id IN (SELECT Subscription.actors_id FROM Subscription WHERE Subscription.user_id = 96)
6bc51xsx

6bc51xsx1#

我猜等价的连接查询将类似于

SELECT c.*, a.contend_id as views 
FROM Content c
JOIN Actors a ON a.contend_id = c.r_id
JOIN Subscription s ON a.actors_id  = s.actors_id
WHERE s.user_id = 96

另外,不要使用旧的语法来联接表。请使用带有join关键字的显式语法

相关问题