MySQL Join +“WHERE something = MAX(something)”

时间:2012-06-23 03:38:21

标签: mysql join left-join

我有几张桌子需要加入。表格是:

玩家

  • 如first_name
  • 姓氏
  • 性别
  • LOCATION_ID
  • (其他无关列)

score_entries

  • 得分
  • 日期时间
  • player_id
  • (其他无关列)

我需要根据player_id加入他们,并且只想选择players.location_id最大的记录。所以像这样:

SELECT
players.first_name,
players.last_name,
players.gender,
score_entries.score,
score_entries.datetime as jump_date
players.location_id,
FROM score_entries
LEFT JOIN players
ON score_entries.player_id = players.id
WHERE gender="m"
AND location_id="***(ONLY THE HIGHEST LOCATION_ID VALUE IN THE TABLE)***"

1 个答案:

答案 0 :(得分:1)

请尝试以下查询

SELECT 
    players.first_name, 
    players.last_name, 
    players.gender, 
    score_entries.score, 
    score_entries.datetime as jump_date, 
    players.location_id
FROM score_entries 
LEFT JOIN players 
ON score_entries.player_id = players.id 
WHERE gender="m" 
AND players.location_id = (SELECT MAX(location_id) from players)