将2个表与左连接组合的问题

时间:2013-02-03 23:15:34

标签: php mysql

我会尽力解释这个问题。 我有两个表“users1213”,这是一个玩家表和“Loanperiodes”。现在我想立即用sql-query获取目前在俱乐部的球员名单。如果他们被租借到另一个俱乐部,他们就不必在名单上。俱乐部也有可能借给球员,所以这些球员也必须在名单上。所以我现在有这个(俱乐部有一个id为“1”而球队也有一个id为“1”):

SELECT users1213.id, surname, name, team, club, loanclub
FROM users1213
LEFT JOIN loanperiode ON users1213.id = loanperiode.player
WHERE users1213.status =  'player'
AND (
(
users1213.club !=  '1'
AND loanperiode.loanclub =  '1'
AND loanperiode.begin <=  '2013-02-03'
AND loanperiode.end >=  '2013-02-03'
AND (
uitleenperiodes.team_id =  '1'
)
)
OR (
users1213.club =  '1'
AND users1213.team =  '1'
AND (
loanperiode.loanclub IS NULL 
OR (
loanperiode.loanclub IS NOT NULL 
AND (
loanperiode.begin <  '2013-02-03'
AND loanperiode.end <  '2013-02-03'
)
OR (
uitleenperiodes.begin >  '2013-02-03'
AND uitleenperiodes.end >  '2013-02-03'
)
)
)
)
)
GROUP BY users1213.id
ORDER BY name
LIMIT 0 , 30

通过这个查询我得到了一个好的结果,但有一个问题,当有人有2个贷款周期。例如,PLAYER1现在借给CLUB A,因此他可能没有列出。但是当PLAYER1也有一个已经过期的贷款周期时,对于CLUB B,由于LEFT JOIN,PLAYER1将被列出。有没有一个解决方案可以通过查询来解决这个问题,或者我在运行数组时必须检查一下吗?

非常感谢!

1 个答案:

答案 0 :(得分:0)

SELECT users1213.id, surname, name, team, club, loanclub
FROM users1213
LEFT JOIN loanperiode ON users1213.id = loanperiode.player
    AND '2013-02-03' BETWEEN loanperiode.begin AND loanperiode.end

WHERE
loanperiode.loanclub =  '1'
OR (loanperiode.loanclub IS NULL -- I suppose this happens only when there is no loan between those dates so nothing LEFT JOINed
AND users1213.club = '1')

ORDER BY name

此示例假设用户一次只能获得一笔贷款(是的,他可以在历史记录中结束更多贷款,但只有一笔在今天之前开始,在将来结束)。