簡體   English   中英

連接2個表以獲得2個相關記錄Mysql PHP

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

我有兩個這樣的表:

# 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 

我正在嘗試從比賽表中獲取包含兩個球隊信息的列表,我想要一些東西:

Team A (England)  vs Team B (France)

我嘗試了這個,但是我得到了錯誤的團隊信息,我的查詢肯定有問題。

這是我的查詢:

  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`

提前致謝!

我只是用postgres在測試機上弄弄它。 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

因此,您的實際查詢是正確的。 較干凈的將是以下內容:

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

但是您的問題顯然不是SQL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM