按查询分组的SQL查询计数不按预期工作

时间:2014-02-25 15:12:33

标签: mysql sql

我的目标是获得一张能够计算游戏正确答案的表格。

例如我想要这个

| G.Name | E.Action 
| game 1 | correctAnswer 
| game 1 | correctAnswer 
| game 2 | correctAnswer 
| game 3 | correctAnswer 
| game 3 | correctAnswer 

成为这个

| G.Name | Count(*) 
| game 1 | 2 
| game 2 | 1 
| game 3 | 2 

问题是我得到了这个:

| G.Name | Count(*)
| game 1 | 5 
| game 2 | 5 
| game 3 | 5 

其中5是2 + 1 + 2的总和

这是我的查询

  SELECT G.Name, Count(*)
    FROM enduser EU
         INNER JOIN prescription P 
                    ON EU.UserRefID = P.EndUserRefID
         INNER JOIN prescriptiongame PG 
                    ON PG.PrescriptionRefID = P.PrescriptionID
         INNER JOIN games G 
                    ON G.GameID = PG.GameRefID
         INNER JOIN session S 
                    ON S.PrescriptionRefID = P.PrescriptionID
         INNER JOIN entries E 
                    ON E.SessionGameRefID = S.Session
   WHERE P.EndUserRefID = 889
         AND E.Action =  'correctAnswer'
GROUP BY G.Name
ORDER BY G.Name

我怎么能解决这个问题,当我用谷歌搜索人们使用相同的方法,但他们得到了良好的结果

提前致谢

4 个答案:

答案 0 :(得分:0)

我敢打赌,你的一个联盟正在夸大结果。将查询删除至关键表:prescriptionsessionentries。你还得到过多的结果吗?如果没有,请尝试一次添加一个连接,直到您计算过多为止。

答案 1 :(得分:0)

您的联接以某种方式乘以行数。当您沿着彼此不相关的不同维度连接表时会发生这种情况。这是一个常见问题,但我不了解您的数据结构,因此以下是最佳猜测。

您可以使用count(distinct)修复您的示例。所以试试这个:

SELECT G.Name, Count(distinct SessionGameRefID)

sessiongame之间是否存在关系?

我想知道你的查询的简化是否会解决问题(它会删除前两个表):

  SELECT G.Name, Count(*)
    FROM prescriptiongame PG 
         INNER JOIN games G 
                    ON G.GameID = PG.GameRefID
         INNER JOIN session S 
                    ON S.PrescriptionRefID = PG.PrescriptionRefID
         INNER JOIN entries E 
                    ON E.SessionGameRefID = S.Session
   WHERE PG.EndUserRefID = 889
         AND E.Action =  'correctAnswer'
  GROUP BY G.Name
  ORDER BY G.Name;

答案 2 :(得分:0)

假设需要所有连接,请尝试以下查询:

  SELECT G.Name, Count(G.Name)
    FROM enduser EU
         INNER JOIN prescription P 
                    ON EU.UserRefID = P.EndUserRefID
         INNER JOIN prescriptiongame PG 
                    ON PG.PrescriptionRefID = P.PrescriptionID
         INNER JOIN games G 
                    ON G.GameID = PG.GameRefID
         INNER JOIN session S 
                    ON S.PrescriptionRefID = P.PrescriptionID
         INNER JOIN entries E 
                    ON E.SessionGameRefID = S.Session
   WHERE P.EndUserRefID = 889
         AND E.Action =  'correctAnswer'
GROUP BY G.Name
ORDER BY G.Name

答案 3 :(得分:0)

perl -v

This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux
file `which perl`
/sv/app/perx/third-party/bin/perl: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, not stripped

 2.198696207 - 2.134326286: 0.0643699210000004
 2.198696207 - 2.134326286: 0.047901175