获得重复的sql结果

时间:2016-12-08 05:55:54

标签: mysql sql angularjs node.js

我有3个表:用户,文章和投票

| Users |    | Articles |    |   Votes   |
|   id  |    |    id    |    |  userId   |
|  name |    |  title   |    | articleId |
| email |    |  userId  |    |    type   |

我希望获得用户名单,其中包括Count voteup和Count votedown for each one。

我正在测试此查询:

SELECT u.id,u.name,u.email,
(SELECT COUNT(*) FROM votes as v WHERE v.type=1 AND v.articleId IN 
   (SELECT a.id From articles as a WHERE a.userId = u.id) ) AS totalvoteup,
(SELECT COUNT(*) FROM votes as v WHERE v.type=0 AND v.articleId IN 
   (SELECT a.id From articles as a WHERE a.userId = u.id) ) AS totalvotedown
FROM users as u

当我通过phpmyadmin测试它时,我有我想要的列表(结果编号与表中的用户数相匹配),但是当我尝试通过Node服务器(来自AngularJs或Postman)时,我有' m得到重复的结果:

{
"users": [
[
  {
    "id": 1,
    "name": "John Lennon",
    "email": "johnlennon@gmail.com",
    "totalvoteup": 0,
    "totalvotedown": 0
  },
  {
    "id": 2,
    "name": "John Lennon 2",
    "email": "johnlennon2@gmail.com",
    "totalvoteup": 0,
    "totalvotedown": 0
  },
  {
    "id": 3,
    "name": "John Lennon 3",
    "email": "johnlennon3@gmail.com",
    "totalvoteup": 0,
    "totalvotedown": 1
  },
  {
    "id": 4,
    "name": "John Lennon 4",
    "email": "johnlennon4@gmail.com",
    "totalvoteup": 0,
    "totalvotedown": 0
  }
],
[
  {
    "id": 1,
    "name": "John Lennon 1",
    "email": "johnlennon1@gmail.com",
    "totalvoteup": 0,
    "totalvotedown": 0
  },
  {
    "id": 2,
    "name": "John Lennon 2",
    "email": "johnlennon2@gmail.com",
    "totalvoteup": 0,
    "totalvotedown": 0
  },
  {
    "id": 3,
    "name": "John Lennon 3",
    "email": "johnlennon3@gmail.com",
    "totalvoteup": 0,
    "totalvotedown": 1
  },
  {
    "id": 4,
    "name": "John Lennon 4",
    "email": "johnlennon4@gmail.com",
    "totalvoteup": 0,
    "totalvotedown": 0
  }
]
]
}

有任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

我不是Java人,也不确定问题,但查询可以用更好的方式编写

SELECT DISTINCT u.id,
       u.name,
       u.email,
       coalesce(totalvoteup,0) as totalvoteup,
       coalesce(totalvotedown,0) as totalvotedown
FROM   users AS u
       LEFT JOIN (SELECT DISTINCT id,userId FROM articles) a
              ON a.userId = u.id
       LEFT JOIN (SELECT Count(CASE WHEN v.type = 1 THEN 1 END) AS totalvoteup,
                         Count(CASE WHEN v.type = 0 THEN 1 END) AS totalvotedown,
                         v.articleId
                  FROM   votes v
                  GROUP  BY v.articleId) v
              ON a.id = v.articleId 

由于我喜欢查询优化,可能无法帮助您解决分享问题