简体   繁体   中英

MySQL select from two tables

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 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

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