简体   繁体   中英

Problems with combining 2 tables with Left Join

I'll try to explain the problem as good as possible. I have two tables "users1213" which is a table of players and "Loanperiodes". Now I'm trying to get immediately with a sql-query a list of players who is at the moment at the club. If they are on loan to another club they don't have to be on the list. It's also possible that the club is loaning a player so these players have to be on the list as well. So I have this for the moment (the club has an id "1" and the team has also an 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

With this query I get a good result but there is 1 problem, when someone had got 2 loanperiodes. For example PLAYER1 is loaned now to CLUB A so he may not be listed. But when PLAYER1 has also got a loanperiode which has already expired, to CLUB B, PLAYER1 will be listed because of the LEFT JOIN. Is there a solution to solve this with a query or must I check afterwards when I'm running the array?

Many thanks!

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

This example supposes that user can have only one loan at once (yes, he can have more loans ended in history, but only one begins before today and ends in the future).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM