php - 使用 MySQL 在一个查询中连接三个表

标签 php mysql sql

我有表命名

**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_id,因为我知道 user_id 值,之后需要从 Actors 内容表中获取 content_id,最后从内容表中获取 r_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)

最佳答案

我想等效的连接查询看起来像

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 关键字的显式语法

关于php - 使用 MySQL 在一个查询中连接三个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51408805/

相关文章:

php - 如果超过 512 字节,TextArea 不会保存到 mySQL

PHP MySQL 有没有办法从错误中获取列键

mysql - 如何 LEFT JOIN 具有相同列名的两个表

php - 即使在主类别上,页面也会返回子类别的 ID

sql - 如何使用自连接更快地进行查询?

sql - 数据库停机后如何使Rails自动重新建立数据库连接

php - MySql 查询 - 检查数据是否存在,如果存在则获取 id,如果不存在则添加数据并获取 id

php - 创建搜索功能,为什么是 "Warning: Division by zero in/path/test.php on line 29 Query was empty"

mysql - 尝试编写 MySQL 触发器以替换 phpmyadmin 上的 CHECK 约束时出现语法错误

php - 选择子类别和没有子类别的父类别