简体   繁体   English

用左联接合并2个表的问题

[英]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". 我有两个表“ users1213”,它是玩家表和“ Loioperiodes”表。 Now I'm trying to get immediately with a sql-query a list of players who is at the moment at the club. 现在,我想立即通过sql查询获取目前在俱乐部的球员列表。 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"): 所以我现在有这个(俱乐部的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

With this query I get a good result but there is 1 problem, when someone had got 2 loanperiodes. 通过此查询,我得到了不错的结果,但是当有人获得2个借贷期时,有1个问题。 For example PLAYER1 is loaned now to CLUB A so he may not be listed. 例如,PLAYER1现在借给了CLUB A,因此他可能没有列出。 But when PLAYER1 has also got a loanperiode which has already expired, to CLUB B, PLAYER1 will be listed because of the LEFT JOIN. 但是,当PLAYER1也有一个已到期的借贷期限时,到CLUB B时,PLAYER1将因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). 此示例假设用户一次只能获得一笔贷款(是的,他可以在历史记录中拥有更多的贷款,但是只有一笔在今天之前开始,并在将来结束)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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