如何在MySQL中获取同一列的两个不同值

时间:2019-01-08 04:35:10

标签: mysql

我有两个表{match_id}_match_main表和users表。 match_main表存储了所有参加比赛的玩家。

我想选择在两个不同的列中的同一张桌子中为两个球队效力的名字球员。

另一个表match_master存储正在播放的所有比赛:

match_master的描述:match_id,team1_id,team2_id

{match_id}_match_main的描述是:player_id,team_id,目标,黄色,红色。

users的描述是:player_id,player_name。

我尝试使用连接

select B.Name as home_player_name,B1.Name as away_player_name 
from {match_id}_match_main A 
inner join users B on A.player_id=B.player_id,
users B1
inner join {match_id}_match_main A1 on A1.player_id=B1.player_id
where A.team_id='t1' and A1.team_id='t2';

但是此查询未提供不同的值,而是提供了重复的值。

1 个答案:

答案 0 :(得分:0)

我认为此查询将为您提供所需的结果。它从team_id中查找不同的match_main值,然后再次从JOINmatch_main两次,以获取每个团队的球员列表以及行号,该行号是用来确保我们不会重复成对的玩家:

SELECT u1.player_name, u2.player_name
FROM (SELECT MIN(team_id) AS team_1, MAX(team_id) AS team_2 FROM match_main) teams
JOIN (SELECT *, @rn1 := @rn1 + 1 AS rownumber
      FROM match_main
      CROSS JOIN (SELECT @rn1 := 0) r
      ORDER BY team_id ASC) m1 ON m1.team_id = teams.team_1
JOIN (SELECT *, @rn2 := @rn2 + 1 AS rownumber
      FROM match_main
      CROSS JOIN (SELECT @rn2 := 0) r
      ORDER BY team_id DESC) m2 ON m2.team_id = teams.team_2 AND m2.rownumber = m1.rownumber
JOIN users u1 ON u1.player_id = m1.player_id
JOIN users u2 ON u2.player_id = m2.player_id

我已经创建了一个小型demo on dbfiddle,以便您可以在工作中看到它并使用它。

第一个派生表:

SELECT MIN(team_id) AS team_1, MAX(team_id) AS team_2 FROM match_main

在每次比赛中找到两个独立的球队。第二和第三派生表:

SELECT *, @rn1 := @rn1 + 1 AS rownumber
FROM match_main
CROSS JOIN (SELECT @rn1 := 0) r
ORDER BY team_id ASC

基本上是相同的。他们为match_main表中的每一行生成行号,按team_id升序或降序排列,以使每个团队的球员都在表的上半部分。 m2.rownumber = m1.rownumber确保在最终结果中我们吸引了每个团队的球员。最后两个JOINusers使我们能够从该表中获取玩家名称。

更新

要使用match_master中的球队ID(以确保对本垒打和客队球员进行正确排序),您将需要在查询中使用{match_id}值(共有3个位置);这样的事情应该起作用:

SELECT u1.player_name, u2.player_name
FROM match_master teams
JOIN (SELECT *, @rn1 := @rn1 + 1 AS rownumber
      FROM {match_id}_match_main
      CROSS JOIN (SELECT @rn1 := 0) r
      ORDER BY team_id ASC) m1 ON m1.team_id = teams.team1_id
JOIN (SELECT *, @rn2 := @rn2 + 1 AS rownumber
      FROM {match_id}_match_main
      CROSS JOIN (SELECT @rn2 := 0) r
      ORDER BY team_id DESC) m2 ON m2.team_id = teams.team2_id AND m2.rownumber = m1.rownumber
JOIN users u1 ON u1.player_id = m1.player_id
JOIN users u2 ON u2.player_id = m2.player_id
WHERE teams.match_id = {match_id}