从一个表查询与两个表(MySQL)的关系

时间:2018-04-05 11:07:11

标签: mysql

早上好。寻找建议。

我有三张桌子:

匹配| MatchID | MatchDateTime |等等... 外表| AppearanceID | AppearancePlayerID | AppearanceMatchID 替换| SubstitutionID | SubstitutionPlayerIDIn | SubstitutionMatchID

我试图以日期顺序显示匹配列表,其中包含完整外观(包含在外观中)或替换外观(包含在替换中)形式的玩家X($ id)。一名球员不会同时出现在比赛中。

结果看起来像这样:

matchid | matchdate   | type
1       | 2012-06-30  | (sub)
18      | 2012-07-10  | (full)
24      | 2012-07-17  | (full)
25      | 2012-07-24  | (full)
28      | 2012-07-31  | (full)
33      | 2012-09-05  | (sub)

变量$ id是我希望显示此数据的播放器的ID。

我的下面尝试中还包含了一些其他表,这些表可用于启用更多匹配数据,但到目前为止这已经取得了进展,但没有返回任何行。 :/

SELECT
  M.MatchID AS matchid,
  DATE_FORMAT(M.MatchDateTime, '%b %D, %Y') AS time,
  DATE_FORMAT(M.MatchDateTime, '%d/%m/%y') AS date,
  M.MatchPlaceID AS place,
  M.MatchNeutral AS neutral,
  O.OpponentShort AS opponent,
  O.OpponentID AS oppid,
  MT.MatchTypeName AS matchtype,
  M.MatchAdditionalType AS add_type,
  M.MatchGoals AS goalsfor,
  M.MatchGoalsOpponent AS goalsagainst,
  M.MatchOvertime AS overtime,
  M.MatchPenaltyShootout AS penalties,
  M.MatchPenaltyGoals AS pensfor,
  M.MatchPenaltyGoalsOpponent AS pensagainst
FROM    
  matches M, opponents O, matchtypes MT, appearances A, substitutions S
WHERE
  (A.AppearanceMatchID = M.MatchID AND A.AppearancePlayerID = $id) OR 
  (S.SubstitutionMatchID = M.MatchID AND S.SubstitutionPlayerIDIn = $id) AND M.MatchOpponent = O.OpponentID AND M.MatchTypeID = MT.MatchTypeID
ORDER BY
  M.MatchDateTime DESC

我正在使用MYSQL 5.6。

1 个答案:

答案 0 :(得分:1)

试试这个

SELECT
  M.MatchID AS matchid
  DATE_FORMAT(M.MatchDateTime, '%b %D, %Y') AS time,
  DATE_FORMAT(M.MatchDateTime, '%d/%m/%y') AS date,
  M.MatchPlaceID AS place,
  M.MatchNeutral AS neutral,
  O.OpponentShort AS opponent,
  O.OpponentID AS oppid,
  MT.MatchTypeName AS matchtype,
  M.MatchAdditionalType AS add_type,
  M.MatchGoals AS goalsfor,
  M.MatchGoalsOpponent AS goalsagainst,
  M.MatchOvertime AS overtime,
  M.MatchPenaltyShootout AS penalties,
  M.MatchPenaltyGoals AS pensfor,
  M.MatchPenaltyGoalsOpponent AS pensagainst
FROM    
  matches M
inner join
  opponents O on M.MatchOpponent = O.OpponentID
inner join
  matchtypes MT on M.MatchTypeID = MT.MatchTypeID
left join
  appearances A on A.AppearanceMatchID = M.MatchID AND A.AppearancePlayerID = $id
left join
  substitutions S on S.SubstitutionMatchID = M.MatchID AND S.SubstitutionPlayerIDIn = $id 
WHERE
  (A.AppearanceID is not null) OR 
  (S.SubstitutionID is not null)
ORDER BY
  M.MatchDateTime DESC

并考虑阅读有关联接的内容,因为通过指定要从中选择的表列表而不是显式加入它们,您可以在MySQL选择交叉连接时遇到这种情况