从具有不同条件SQL的表中选择一个值

时间:2014-05-07 16:02:33

标签: mysql sql sql-server

TABLE播放器

idPlayer | name  |

    1    | name1 |
    2    | name2 |
    3    | name3 |
    4    | name4 |

表匹配

idMatch  |  idPlayer1 | idPlayer2 | date  |

   1     |      1     |     2     | 03-03 |
   2     |      3     |     4     | 03-03 |
   3     |      1     |     4     | 03-03 |   

Expeted

idMatch  |   player1  |   player2 | date  |

   1     |    name1   |    name2  | 03-03 |
   2     |    name3   |    name4  | 03-03 |
   3     |    name1   |    name4  | 03-03 |

我尝试了很多代码但仍未找到解决方案。

2 个答案:

答案 0 :(得分:1)

试试这个:

 Select t1.idMatch AS idMatch, p1.name AS player1, p2.name AS player2, t1.date AS date
 FROM matches t1
 INNER JOIN player p1 ON t1.idPlayer1 = p1.idPlayer
 INNER JOIN player p2 ON t1.idPlayer2 = p2.idPlayer

这应该为你正确解码玩家。

答案 1 :(得分:0)

我做了这个

SELECT idMatch,
(SELECT name FROM t1 WHERE t2.idPlayer1=t1.idPlayer) as name1, 
(SELECT name FROM t1 WHERE t2.idPalyer2=t1.idplayer) as name2, 
date
FROM calendario

它有效。