1

我真的不知道如何寻找这个问题的解决方案,没有找到任何具体的东西,所以这里......

我有四个表,让我们简化它们:

  players
  =======
  id    name    surname
  1     John    Arbuckle
  2     Walter  White
  3     Don Draper
  4     Louis   CK
  5     Tyrion  Lannister
  6     Abed    Nadir

  sports
  ======
  id    sport
  1     football
  2     handball

  positions
  =========
  id    name    sport_id
  1     goalie  1
  2     defense 1
  3     attack  1
  4     goalie  2
  5     pivot   2
  6     wing    2
  7     center  2

  player_position
  ===============
  player_id position_id
  1         1
  1         2
  1         5
  2         7
  2         5
  3         2
  4         2
  5         1
  5         3
  6         7
  6         5

因此,玩家可以在多个位置上进行多项运动。首先,我必须显示某项运动的球员名单,包括他们所打位置的列。

我开始使用的是 JOIN 语句,我将在其中加入这些表并为每个玩家 ID 设置多行。这很接近,但不是很正确。我需要得到的是这样的表格:

足球

    ID  name    surname     position
    1   John    Arbuckle    PHP array(goalie,defense)

手球

    ID  name    surname     position
    1   John    Arbuckle    PHP array(pivot)

编辑:所以我正在寻找的是 GROUP_CONCAT()。多谢你们!

4

3 回答 3

2
select p.id, p.name, p.surname, group_concat(po.name)
from players p 
inner join player_position pp on pp.player_id = p.id
inner join positions po on po.id = pp.position_id
inner join sports s on s.id = po.sport_id
where s.sport = 'football'
group by p.id

请参阅此SQLFiddle 示例

于 2012-05-20T14:56:09.860 回答
1

我不确定这是否万无一失(未经测试),但是……</p>

SELECT pp.`player_id` AS 'ID',s.`id` AS 'sport_id',s.`sport`,ps.`name` AS 'position',pl.`name`,pl.`surname` FROM `sports` s
INNER JOIN `positions` ps ON s.`id`=ps.`sport_id`
INNER JOIN `player_position` pp ON pp.`position_id`=ps.`id`
INNER JOIN `players` pl ON pl.`id`=pp.`player_id`
ORDER BY s.`id`,pp.`player_id`,ps.`id`

这是一个更详细的版本:

SELECT
    s.`id` AS 'sport_id',s.`sport`,
    ps.`id` AS 'position_id',ps.`name` AS 'position',
    pl.`id` AS 'player_id',pl.`name`,pl.`surname`
FROM `sports` s
INNER JOIN `positions` ps ON s.`id`=ps.`sport_id`
INNER JOIN `player_position` pp ON pp.`position_id`=ps.`id`
INNER JOIN `players` pl ON pl.`id`=pp.`player_id`
ORDER BY s.`id`,pp.`player_id`,ps.`id`
于 2012-05-20T14:44:04.000 回答
1

对于足球:

SELECT players.name, players.surname, positions.name 
FROM players, sports, positions, player_position 
WHERE sports.id = 1 AND positions.sport_id = sports.id AND payer_position.position_id = positions.id AND players.id = player_position.player_id;

对于手球:

SELECT players.name, players.surname, positions.name 
FROM players, sports, positions, player_position 
WHERE sports.id = 2 AND positions.sport_id = sports.id AND payer_position.position_id = positions.id AND players.id = player_position.player_id;
于 2012-05-20T14:45:10.757 回答