无论where子句如何获取表的计数

时间:2017-02-11 15:50:55

标签: mysql

我正在构建一个收藏网站,我目前正在处理的事情之一是查询某个用户在一系列中有多少游戏的查询,该位工作正常以及以下查询输出这个:



 <table style="width:100%;text-align:center">
  <tr>
    <th>user_account_id</th>
    <th>series_id</th>
    <th>Name</th>
    <th>COUNT(g.id)</th>
  </tr>
  <tr>
    <td>1</td>
    <td>7</td>
    <td>Halo</td>
    <td>2</td>
  </tr>
  <tr>
    <td>1</td>
    <td>11</td>
    <td>Call of Duty</td>
    <td>6</td>
  </tr> 
  <tr>
    <td>1</td>
    <td>3</td>
    <td>Forza</td>
    <td>3</td>
  </tr>    
</table> 
&#13;
&#13;
&#13;

SELECT uc.user_account_id,
   g.series_id,
   gs.name,
   COUNT(g.id)
FROM user_collections uc
LEFT JOIN games g
ON g.id = uc.game_id
LEFT JOIN games_series gs
ON gs.id = g.series_id
WHERE uc.user_account_id = 1
GROUP BY(g.series_id)

我试图根据查询的SELECT部分​​提供的games信息,弄清楚如何从series_id表中获取所有行的完整计数。所以输出反而是:

&#13;
&#13;
 <table style="width:100%;text-align:center">
  <tr>
    <th>user_account_id</th>
    <th>series_id</th>
    <th>Name</th>
    <th>COUNT(g.id)</th>
    <th>Full Count</th>
  </tr>
  <tr>
    <td>1</td>
    <td>7</td>
    <td>Halo</td>
    <td>2</td>
    <td>10</td>
  </tr>
  <tr>
    <td>1</td>
    <td>11</td>
    <td>Call of Duty</td>
    <td>6</td>
    <td>12</td>
  </tr> 
  <tr>
    <td>1</td>
    <td>3</td>
    <td>Forza</td>
    <td>3</td>
    <td>8</td>
  </tr>    
</table> 
&#13;
&#13;
&#13;

我尝试过做一个子选择查询,但看起来你不能根据选择查询的列做一个WHERE子句,所以我不太清楚从哪里去这里。

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

一种方法是在SELECT子句中使用相关的子查询

SELECT uc.user_account_id,
   g.series_id,
   gs.name,
   COUNT(g.id),
   (SELECT COUNT(*) FROM games g1 WHERE g1.series_id = gs.id) as `Full Count`
FROM user_collections uc
JOIN games g
ON g.id = uc.game_id
JOIN games_series gs
ON gs.id = g.series_id
WHERE uc.user_account_id = 1
GROUP BY(g.series_id)