简体   繁体   English

MySQL 查询未按预期提供结果

[英]MySQL query not giving results as expected

Below are two mysql tables.下面是两个mysql表。 I want to check if the two people are in teams from Table: Teams and then getting their name and email from Table: Registration.我想从 Table: Teams 中检查这两个人是否在团队中,然后从 Table: Registration 获取他们的姓名和电子邮件。 I am having a hard time writing a mysql query for it.我很难为它编写 mysql 查询。

Table: Registration表:注册

id: 1      name:jason        email:jason@xyz.com
id: 2      name:kim          email:kim@xyz.com
id: 3      name:tim          email:tim@xyz.com

Table:Teams表:团队

team_id: 1      person1Id: 1       person2Id: 2
team_id: 2      person1Id: 1       person2Id: 3

您可以从 Teams 表中选择两个 ID 并使用in子句从注册表中获取姓名和电子邮件作为

select name, email from Registration where id in(select person1Id, person2Id from Teams where team_id=1)

You have to join the registration table twice and give them a unique alias你必须两次加入注册表并给他们一个唯一的别名

Schema (MySQL v8.0)架构 (MySQL v8.0)

CREATE TABLE Teams (
  `team_id` INTEGER,
  `person1Id` VARCHAR(9),
  `person2Id` INTEGER
);

INSERT INTO Teams
  (`team_id`, `person1Id`, `person2Id`)
VALUES
  ('1', '1', '2'),
  ('1', '1', '3');

CREATE TABLE Registration (
  `id` INTEGER,
  `name` VARCHAR(5),
  `email` VARCHAR(13)
);

INSERT INTO Registration
  (`id`, `name`, `email`)
VALUES
  ('1', 'jason', 'jason@xyz.com'),
  ('2', 'kim', 'kim@xyz.com'),
  ('3','tim','tim@xyz.com');

Query #1查询#1

SELECT 
    t.team_id,r1.name,r1.email,r2.name,r2.email
FROM Teams t
INNER JOIN Registration r1 ON t.person1Id = r1.id
INNER JOIN Registration r2 ON t.person2Id = r2.id;

| team_id | name  | email         | name | email       |
| ------- | ----- | ------------- | ---- | ----------- |
| 1       | jason | jason@xyz.com | kim  | kim@xyz.com |
| 1       | jason | jason@xyz.com | tim  | tim@xyz.com |

View on DB Fiddle在 DB Fiddle 上查看

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

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