简体   繁体   English

连接2个表以获得2个相关记录Mysql PHP

[英]Join 2 tables to get 2 related records Mysql PHP

I have two tables like so: 我有两个这样的表:

# Match 
id, team1_id , team2_id
-----------------------
1, 10, 20
2, 10, 50



# Team 
id, team_name, team_country
---------------------------
10, team A , England
20, team B , France 

I'm trying to get the list from Match table with both teams info, I wanna some thing like : 我正在尝试从比赛表中获取包含两个球队信息的列表,我想要一些东西:

Team A (England)  vs Team B (France)

I tried this one, but I got false team info, some thing wrong with my query for sure. 我尝试了这个,但是我得到了错误的团队信息,我的查询肯定有问题。

Here's my query : 这是我的查询:

  SELECT `match`.*,
  `t1`.`team_country` as team1_country,
  `t2`.`team_country` as team2_country
  FROM `match`,
  `team` t1 , `team` t2
  WHERE `match`.`team1_id` = `t1`.`id` and `match`.`team2_id` = `t2`.`id`

Thanks in advance! 提前致谢!

I just fiddled it on my testmachine with postgres. 我只是用postgres在测试机上弄弄它。 The SQL shouldn't be different: SQL不应不同:

lara=# create table match ( id serial primary key, team1 int, team2 int);
CREATE TABLE
lara=# create table teams ( id serial primary key, name text, country text);
CREATE TABLE
lara=# insert into match(id, team1, team2) values (1,1,2),(2,1,3),(3,2,1);
INSERT 0 3
lara=# select * from match;
 id | team1 | team2
----+-------+-------
  1 |     1 |     2
  2 |     1 |     3
  3 |     2 |     1
(3 rows)

lara=# insert into teams values (1, 't1', 'en');
INSERT 0 1
lara=# insert into teams values (2, 't2', 'de');
INSERT 0 1
lara=# insert into teams values (3, 't3', 'fr');
INSERT 0 1
lara=# select * from match m left join teams t1 on t1.id=m.team1 left join teams t2 on t2.id=m.team2;
 id | team1 | team2 | id | name | country | id | name | country
----+-------+-------+----+------+---------+----+------+---------
  1 |     1 |     2 |  1 | t1   | en      |  2 | t2   | de
  2 |     1 |     3 |  1 | t1   | en      |  3 | t3   | fr
  3 |     2 |     1 |  2 | t2   | de      |  1 | t1   | en

So your actual query is correct. 因此,您的实际查询是正确的。 A cleaner one would be the following: 较干净的将是以下内容:

SELECT * FROM match m 
LEFT JOIN teams t1 ON t1.id=m.team1 
LEFT JOIN teams t2 ON t2.id=m.team2;

But your problem is obviously not the SQL. 但是您的问题显然不是SQL。

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

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