我的左外连接查询问题

时间:2018-04-12 14:34:52

标签: sql left-join

这是我的表格,

enter image description here

如果用户下注或未下注,我正试图获取包含详细信息的免费投注列表。这是我写的查询以获取相同的详细信息,

select DISTINCT tbl_CreateFreeBet.FreeBetID, 
        tbl_CreateFreeBet.FreeBetDescription, 
        tbl_CreateFreeBet.FreeBetAmount, 
        tbl_CreateFreeBet.TournamentID, 
        tbl_CreateFreeBet.MatchID, 
        tbl_UserFreeBets.UserForYes, 
        tbl_UserFreeBets.UserForNo, 
        tbl_UserFreeBets.UserForNoBets  
from tbl_CreateFreeBet left outer join tbl_UserFreeBets
on tbl_CreateFreeBet.MatchID = 1 and
tbl_CreateFreeBet.MatchID = tbl_UserFreeBets.MatchID and 
tbl_CreateFreeBet.FreeBetID = tbl_UserFreeBets.FreeBetID and 
tbl_CreateFreeBet.TournamentID = tbl_UserFreeBets.TournamentID and 
(tbl_UserFreeBets.UserForYes = 'User2' or tbl_UserFreeBets.UserForNo = 
'User2')

当matchID的tbl_CreateFreeBet表中有数据时,这工作正常。但是如果没有数据,则此查询不会返回预期结果。

例如:使用tbl_CreateFreeBet.MatchID = 1,我需要获得matchID = 1的所有免费投注,以及传入用户的详细信息,如果已下注'是'或'否'。这很好,因为在tbl_CreateFreeBet中有MatchId = 1的数据。

但是,当传递tbl_CreateFreeBet.MatchID = 2输入时,它失败了。这里没有为MatchID = 2创建免费投注。但仍然会返回MatchID = 1的结果。

如果您知道我的查询需要进行哪些更改,请分享查询。谢谢。

1 个答案:

答案 0 :(得分:2)

LEFT JOIN第一个表的条件应该在WHERE子句中。我想你打算这个逻辑:

select cfb.FreeBetID, cfb.FreeBetDescription, cfb.FreeBetAmount, 
       cfb.TournamentID, cfb.MatchID, 
       ufb.UserForYes, ufb.UserForNo, ufb.UserForNoBets  
from tbl_CreateFreeBet cfb left outer join
     tbl_UserFreeBets ufb
     on cfb.MatchID = ufb.MatchID and 
        cfb.FreeBetID = ufb.FreeBetID and 
        cfb.TournamentID = ufb.TournamentID and 
        (ufb.UserForYes = 'User2' or ufb.UserForNo = 'User2')
where cfb.MatchId = 1