2015-11-01 53 views
1

我有一个查询:该查询是可靠的吗? (多JOIN在SQL)

SELECT matches.id, 
matches.player1, 
matches.player2, 
users.firstname as firstname, 
tournaments.tid as tid, 
users.tempsalt as salt 
FROM matches 
INNER JOIN tournaments 
ON matches.tid = tournaments.tid 
INNER JOIN users 
ON matches.uid = users.uid 
WHERE ((matches.status = 0) 
OR (matches.status = 1)) 
AND (tournaments.status <> 3) 
AND (users.tempsalt = '324234324234') 

三个表 - 比赛比赛用户

  • 比赛(ID,TID,UID, player1,player2,status)
  • users(id,uid,firstname, tempsalt)
  • 比赛(ID,TID,状态)

加了: 火柴[1,3,2,约翰,马克,0] [2,3,NULL,Piter酒店,萨拉,1]

用户[1,3,亚历克斯,346] [2,4,山姆,32423]

比赛[1,3,2] 我想获得的结果: [1 ,约翰,马克,山姆,3,32423]和NULL t oo [2,Piter,Sara,NULL,3,NULL]

如果matches.uid为NULL,则不会有结果。但是我想在match.uid也是NULL时得到结果。在一个SQL查询中可以吗?

+0

编辑你的问题,并提供样本数据和预期的结果。 –

+0

好的,等一下。 – Puristaako

+0

使用'left join'而不是'inner join' –

回答

2

使用left join,并把连接表的条件on子句中

SELECT m.id, m.player1, m.player2, 
     u.firstname as firstname, u.tempsalt as salt, 
     t.tid as tid 
FROM matches m 
LEFT JOIN tournaments t ON m.tid = t.tid 
         AND t.status <> 3 
LEFT JOIN users u ON m.uid = u.uid 
       AND u.tempsalt = '324234324234' 
WHERE m.status in (0,1) 
+0

非常感谢!你拯救了我的一天 – Puristaako