SQL:创建Home&离开查询

时间:2016-12-12 21:45:16

标签: mysql sql

我有以下两个产生以下内容的查询:

mysql>  select f.fixturematchday, f.fixtureid, t.teamname as homeTeam
          from straightred_fixture as f,
               straightred_team as t
          where f.fixturematchday = 15 and f.hometeamid = t.teamid;

+-----------------+-----------+-------------+
| fixturematchday | fixtureid | homeTeam    |
+-----------------+-----------+-------------+
|              15 |    364393 | Hull        |
|              15 |    364394 | Leicester   |
+-----------------+-----------+-------------+
2 rows in set (0.00 sec)

mysql> select f.fixturematchday, f.fixtureid, t.teamname as awayTeam 
         from straightred_fixture as f,
              straightred_team as t 
         where f.fixturematchday = 15 and f.awayteamid = t.teamid;
+-----------------+-----------+----------------+
| fixturematchday | fixtureid | awayTeam       |
+-----------------+-----------+----------------+
|              15 |    364393 | Crystal Palace |
|              15 |    364394 | Man City       |
+-----------------+-----------+----------------+
2 rows in set (0.00 sec)

但我想回复:

+-----------------+-----------+-------------+----------------+
| fixturematchday | fixtureid | homeTeam    | awayTeam       |
+-----------------+-----------+-------------+----------------+
|              15 |    364393 | Hull        | Crystal Palace |
|              15 |    364394 | Leicester   | Man City       |
+-----------------+-----------+-------------+----------------+

我假设需要某种加入。

2 个答案:

答案 0 :(得分:2)

已经在这些查询中执行JOIN。您正在加入straightred_team以获取团队名称。您可以做的是JOIN两次,一次用于f.hometeamid,一次用于f.awayteamid

注意:多次连接同一个表格完全没问题,将表格连接到自身也没问题。

select f.fixturematchday, f.fixtureid,
       th.teamname as homeTeam, ta.teamname as awayTeam
from straightred_fixture as f,
     straightred_team as th,
     straightred_team as ta
where f.fixturematchday = 15
  and f.hometeamid = th.teamid
  and f.awayteamid = ta.teamid;

您也可以使用JOIN .. ON语法编写此查询:

SELECT f.fixturematchday, f.fixtureid,
       th.teamname as homeTeam, ta.teamname as awayTeam
FROM straightred_fixture as f
JOIN straightred_team as th ON f.hometeamid = th.teamid
JOIN straightred_team as ta ON f.awayteamid = ta.teamid
WHERE f.fixturematchday = 15

答案 1 :(得分:2)

SELECT a.fixturematchday, a.fixtureid, 
    (SELECT teamName FROM straightred_team t WHERE t.teamid = a.hometeamid) 
    AS homeTeam, 
    (SELECT teamName FROM straightred_team t WHERE t.teamid = a.awayteamid) 
    AS awayteam
FROM fixturematchday AS a
WHERE a.fixturematchday = 15

我认为两个子选择应该是最简单的方法