简体   繁体   English

MYSQL-如何从第一个表返回数组,并在一个查询中使用该数组从另一个表中选择?

[英]MYSQL - How to return array from first table and select from another table using that array in one query?

I have 2 tables: 我有2张桌子:

1) game_follower (stores which user is following which game): 1)game_follower(存储哪个用户正在关注哪个游戏):

___________________________
| ID  | game_id | user_id |
| 1   |  1      |  1      |
| 2   |  2      |  1      |

2) videos: 2)视频:

__________________________________
| ID  | game_id | content | data |
| 1   |  2      |  blah   | blah |
| 2   |  1      |  blah   | blah |

I'm trying to implement a twitter-style following system, but I'm having trouble writing a query that does the following: 我正在尝试实现Twitter风格的跟踪系统,但是在编写执行以下操作的查询时遇到了麻烦:

  • select multiple game_ids WHERE user_id = "1" 选择多个game_ids,其中user_id =“ 1”
  • from that list of game_ids, select from videos where game_id = (multiple game ids that have been selected from the first query) 从该game_ids列表中,从其中game_id =(从第一个查询中选择的多个游戏ID)的视频中选择

I can do it with separate queries but I've been told that using multiple queries is bad for performance, so how do I do this in with one query? 我可以使用单独的查询来执行此操作,但是有人告诉我使用多个查询会降低性能,那么如何使用一个查询执行此操作?

try this 尝试这个

SELECT v.game_id
FROM videos v
INNER JOIN game_follower gf ON gf.game_id = v.game_id
WHERE gf.user_id = 1

您应该查看JOIN以便通过一个查询来执行此操作(与分别获取数据相比,这大大提高了速度)。

$conn = new PDO(CONNECTION_DETAILS, $username, $pass);
$variable = 1;
$sql = "SELECT game_follower.game_id FROM game_follower ";
$sql .= "INNER JOIN videos ";
$sql .= "ON game_follower.game_id = videos.game_id ";
$sql .= "WHERE game_follower.user_id = :id";
$query = $conn->prepare($sql);
$query->bindParam(':id', $variable, PDO::PARAM_INT);
$query->execute();

Something like that? 这样的东西?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MySQL连接,从一个表返回1行,从另一个表返回多行作为数组或列表 - MySQL join, return 1 row from one table and multiple rows from another table as an array or list 如何从mysql的其他表中选择一个项目和项目数组? - How to select one item and array of items from other table in mysql? 使用数组从mysql表中选择 - select from mysql table using array PHP PDO MySQL根据另一个表的结果数组选择一个表的结果 - php PDO MySQL Select results of one table based on array of results from another table 如何使用数组中的值通过2行比较来选择mysql中的表? - How to select table in mysql with comparison by 2 rows using value from array? 使用从另一表获取的数组从一个表中进行SQL SELECT行 - SQL SELECT rows from one table using an array taken from another table 仅使用 mysql 查询从第二个表中以第一个表作为数组获取记录 - Getting records from second table with first table as array using mysql query only MySQL查询从数组值查询另一个表 - MySQL Query to query another table from array value SELECT * FROM table WHERE value IN array 只返回一个结果 - SELECT * FROM table WHERE value IN array only return one result 如何使用查询遍历从 mysql 数据库表创建的数组并在另一个 php 文件中使用该数组? - How to go through an array which is created from mysql database table with a query and use the array in another php file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM