如何显示指向mySQL中同一个表的两个不同列的值?

时间:2017-04-11 16:32:38

标签: mysql

我有一个"目标"足球联赛的桌子。 我的桌子包含"目标玩家"和#34;目标助手",像这样:

Select idgoal, goal_player, goal_assist from myDB.goal LIMIT 3;

+--------+-------------+-------------+
| idgoal | goal_player | goal_assist |
+--------+-------------+-------------+
|      1 |          14 |          15 |
|      2 |          16 |           0 |
|      3 |          17 |          18 |
+--------+-------------+-------------+

goal_player和goal_assist下的ID都指我的玩家中的特定玩家"表。在rder以可更新的方式呈现我的结果我必须替换实际名称的ID,所以我正在做:

SELECT idgoal, player.player_nickname as goal_player, goal_assist 
   FROM myDB.goal 
   JOIN player 
   ON goal_player = player.idplayer LIMIT 3;

+--------+-------------+-------------+
| idgoal | goal_player | goal_assist |
+--------+-------------+-------------+
|      1 | Maxi        |          15 |
|      2 | El Loco     |           0 |
|      3 | El Bebe     |          18 |
+--------+-------------+-------------+

我无法为goal_player和goal_assist执行此操作,因为这意味着同一个玩家同时执行目标和协助,所以我所做的是使用第一个Join创建一个视图,然后创建第二个视图使用第一个视图,替换" goal_assist"

像魅力一样工作,直到我必须对拥有match_id的名单和22名玩家而不是这些2做同样的事情。

那么,当两列都指向同一个表时,如何用原始表中的值替换ID?

2 个答案:

答案 0 :(得分:1)

您正在寻找两个联接。 。 。以及别名:

SELECT g.idgoal, p.player_nickname as goal_player,
       pa.player_nickname as assist_player 
FROM myDB.goal g JOIN
     player p
     ON g.goal_player = p.idplayer LET JOIN
     player pa
     ON g.goal_assist = pa.idplayer
LIMIT 3;

注意:

  • 所有表都有别名。
  • 所有列引用均为"限定",表示它们引用列所在的表。
  • 你需要两个连接。
  • 第二次加入是LEFT JOIN,用于处理目标没有"协助"播放器。

答案 1 :(得分:0)

你可以试试这个:

SELECT 
    idgoal, 
    (SELECT player_nickname FROM player WHERE player.idplayer = goal_player) as `goal_player_name`,
    (SELECT player_nickname FROM player WHERE player.idplayer = goal_assist) as `goal_assist_name`,
FROM myDB.goal