简体   繁体   English

子查询:根据匹配的用户ID和团队ID从一张表中进行选择,并输出二维数组

[英]subqueries: select from one table based on matching user ids with team ids and output 2 dimensional array

I want to select from login_users to get the following fields: name , username , and user_id . 我想从login_users进行选择,以获取以下字段: nameusernameuser_id

I have a separate table teams with the team_id, as well as the associated user_id , so for example I might have bob with team1, jack with team2, jim with team1, and paul with team2 (all separate rows, not bob and paul -> team2). 我有一个带有team_id以及相关的user_id的单独表teams ,因此,例如,我可能有bob与team1,jack与team2,jim与team1,以及paul与team2(所有单独的行,不是bob和paul->小组2)。 If I provide a function with the team_ id I want to be able to find all the associated user_id s, and then match that data with login_users to output a two dimensional array that has name , username , and user_id of all the team members. 如果我提供一个带有team_ id的函数,我希望能够找到所有关联的user_id ,然后将该数据与login_users匹配,以输出一个二维数组,该数组包含所有团队成员的nameusernameuser_id

SELECT username, user_id, name FROM login_users WHERE EXISTS ( SELECT user_id FROM teams WHERE team_id= $team_id );

I know it has something to do with sub queries I just have never done them before, and I feel that I am on the wrong track. 我知道它与子查询有关,我以前从未做过子查询,而且我觉得自己走错了路。 Furthermore, how would I then go about producing a two dimensional array? 此外,我接下来将如何生成二维数组?

Why only subquery ?? 为什么只子查询?? why not JOIN 为什么不JOIN

SELECT u.username, u.user_id, u.`name` FROM login_users u
JOIN teams t ON(u.user_id = t.user_id)
WHERE team_id= $team_id 

If you want to do this with an "exists" subquery, then it needs to be a correlated subquery: 如果要使用“存在”子查询执行此操作,则它必须是相关子查询:

SELECT username, user_id, name
FROM login_users
WHERE EXISTS (SELECT user_id
              FROM teams
              WHERE team_id = $team_id and
                    teams.user_id = login_users.team_id
             );

You are missing the condition on the user_id . 您缺少user_id上的条件。 That version of the query is saying "get me all rows from login_users when team_id exists in teams ". 该版本的查询的意思是“当team_id存在于teams时, team_idlogin_users获取所有行”。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM