开发者

MySQL select from two tables

开发者 https://www.devze.com 2023-02-23 13:42 出处:网络
I have two tables witch bunch of fields [only needed mentioned] - partners - id [PRI, int] - name [varchar(20)]

I have two tables witch bunch of fields [only needed mentioned]

 - partners
  - id [PRI, int]
  - name [varchar(20)]
  - match [=matches.id]
  - can_call [int]  


 - players
  - registered [0/1]
  - partner [=partners.id]
  - match [=matches.id]

Now, I need one query, that will give one int – how many players can one of partners call;

To get how many players any partner called for any match, I use:

SELECT COUNT(id)
FROM players
WHERE registered=1
  AND partner=PARTNER_ID
  AND match=MATCH_ID

Now, I need to have something like this:

SELECT (can_call-THE_ABOVE) as free
FROM partners
WHERE match=MATCH_ID

And I don't know how to do it :)

The idea is: get free positions for partner we want for the match we want, then substract SELECT COUNT(id) players, that have already been registered for that match by that partner.

Thank you! [I hope I make sense ^_^]

EDIT: I already solved (before the two join answers). I'll probably go with my solution, just because it's simpler; but 开发者_C百科I will look more into the other answers once I'll want to become MySQL advnaced user, thanks everyone ^^


Select P.name
    , P.can_call - Coalesce(Calls.CallCount,0) As CanCall
From partners As P
    Left Join   (
                Select partner, match, Count(*) As CallCount
                From players As P1
                Where registered = 1
                Group By partner, match, 
                ) As Calls
        On Calls.partner = P.id
            And Calls.match = P.match
Where P.match = MATCH_ID


Nevermind, figured it out; it's exactly as my pseudocode above:

SELECT can_call - (SELECT COUNT(id) FROM players WHERE ...) as free
  WHERE match=MATCH_ID AND id=PARTNER_ID

^^


SELECT pa.can_call-COUNT(pl.id)
       AS free
FROM partners pa
  LEFT JOIN players pl
    ON pl.registered=1
      AND pl.partner=pa.id
      AND pl.match=pa.match
WHERE pa.id=PARTNER_ID
  AND pa.match=MATCH_ID
GROUP BY pa.id
       , pa.match
0

精彩评论

暂无评论...
验证码 换一张
取 消