拉入关系数据库字段

时间:2012-06-02 23:49:42

标签: php mysql relational

所以这是我的问题。我有三张桌子:

人员表

person_id, name

活动表

event_id, event_name, event_date

匹配表

match_id, person_a, person_b, winner, event

因此在匹配表中,person_a,person_b和winner是与Person表中的person_id对应的整数。

如果我从Matches表中拉出一行,就会出现这样的结果:

1, 1, 2, 1, Chess Tournament #33

如何使用Person表查找这3个字段(person_a,person_b和winner)以提取其实际名称,以便得到结果?

1, John, Steven, John, Chess Tournament #33

我考虑加入这两个表,但它没有意义,因为我不能只做ON id = id或WHERE id = id。我感谢任何帮助。

1 个答案:

答案 0 :(得分:4)

SELECT
  Matches.match_id AS match_id,
  PersA.name AS persa_name,
  PersB.name AS persb_name,
  IF(winner=person_a,PersA.name,PersB.name) AS winner_name,
  Events.event_name AS event_name
FROM
  Matches
  INNER JOIN Person AS PersA ON Matches.person_a=PersA.person_id
  INNER JOIN Person AS PersB ON Matches.person_b=PersB.person_id
  INNER JOIN Events ON Matches.event=Events.event_id
WHERE
  -- whatever