MySQL从两个表中选择

时间:2011-04-09 19:15:25

标签: php mysql

我有两个表,一堆字段[只需要提到]

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


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

现在,我需要一个查询,即一个int - 一个合作伙伴可以调用多少玩家;

为了获得任何合作伙伴要求任何比赛的球员数量,我使用:

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

现在,我需要这样的事情:

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

我不知道该怎么办:)。

我们的想法是:为我们想要的比赛获得我们想要的合作伙伴的免费位置,然后减去已经由该合作伙伴注册过该比赛的SELECT COUNT(id)玩家。

谢谢! [我希望我有意义^ _ ^]

编辑:我已经解决了(在两个加入答案之前)。我可能会选择我的解决方案,因为它更简单;但是一旦我想成为MySQL的高手用户,我会更多地了解其他答案,谢谢大家^^

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

没关系,弄明白了;它就像我上面的伪代码一样:

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

^^

答案 2 :(得分:1)

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