简体   繁体   English

从MySQL中的JOIN表中拉出同一个表中的多行

[英]Pulling multiple rows from the same table from a JOIN table in MySQL

I have a join table for a schedule (weeks 1, 2, 3, etc) that connects users. 我有一个联系表,用于连接用户的计划(第1,2,3周等)。 Each week in the join table has IDs for two separate users, User A and User B. But there are also multiple rows for each week. 连接表中的每周都有两个独立用户的ID,用户A和用户B.但每周还有多行。 So it looks like this: 所以它看起来像这样:

Schedule Table: 时间表:

-----------------------------------
| week_id |  userA_id  | userB_id |
-----------------------------------
|    1    |     1      |   2      |   
|    1    |     2      |   3      |
----------------------------------

I also have a user table which stores all the information about a user, pretty basic stuff. 我还有一个用户表,存储有关用户的所有信息,非常基本的东西。 So, for instance: 所以,例如:

User Table: 用户表:

-----------------------------------
|    id   |    Name    | Nickname |
-----------------------------------
|    1    |    jason   |   jay    |   
|    2    |    billy   |   bill   |
----------------------------------

What I'd like to do is query my schedule table based on the Week ID and then return a series of users for each Week. 我想要做的是根据周ID查询我的计划表,然后返回每周的一系列用户。 So for instance, give me all the users from week 1 in a series of objects, something like [ { UserA.name: jason, UserB.name: billy }, { UserA.name : billy, UserB.name: jane } ], etc. 例如,从第1周的一系列对象中给我所有用户,例如[{UserA.name:jason,UserB.name:billy},{UserA.name:billy,UserB.name:jane}],等等

I have a sneaking suspicion that this will include multiple JOIN statements, but I can't seem to get it working. 我怀疑这将包含多个JOIN语句,但我似乎无法使其正常工作。 Does anyone know how to structure this MySQL statement? 有谁知道如何构造这个MySQL语句?

One option here is just to join the Schedule table twice to the User table, one join for each user in the relationship. 这里的一个选项是将Schedule表两次加入User表,为关系中的每个用户加入一个join。

SELECT u1.Name,
       u2.Name
FROM Schedule s
INNER JOIN User u1
    ON s.userA_id = u1.id
INNER JOIN User u2
    ON s.userB_id = u2.id
WHERE s.week_id = 1

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

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