SQL / PHP连接表,忽略多个记录

时间:2012-05-20 13:58:47

标签: php sql join

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

我有四张桌子,让我们简化一下:

  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分配多行。这很接近,但不是很正确。而我需要得到的是这样的表:

FOOTBALL

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

手球

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

编辑: 所以我要找的是GROUP_CONCAT()。 谢谢你们!

3 个答案:

答案 0 :(得分: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 example

答案 1 :(得分:1)

我不确定这是否万无一失(未经测试)但是......

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`

答案 2 :(得分: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;