如何LEFT JOIN一个表,采用SUM()或返回0与WHERE子句?

时间:2017-04-21 09:33:24

标签: mysql sql left-join where

获取以下数据:

const csrf = require('lusca').csrf()
const graphqlExpress = require('graphql-server-express').graphqlExpress
const graphiqlExpress  = require('graphql-server-express').graphiqlExpress

server.use((req, res, next) => {
     csrf(req, res, next)
  }
})

server.use('/graphql', (req, res, next) => {
  graphqlExpress( () => {
    const query = req.query.query || req.body.query;
    return {
      schema,
      context: Object.assign({ user }, req.context),
      debug: false,
      formatError(e) { console.log(e) },
    }
  })(req, res, next)
})

server.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql',
}))

我想将付款表LEFT JOIN到users表,而SUM()付款金额= 0:

db.users

id      name
1       David
2       James
3       Mary

db.payments
amount  user_id     paid
5       1           0
55      1           1
94      1           1
5       2           0
55      2           1
94      2           1
5       2           0
55      2           1
94      2           1

问题出在“玛丽' (用户3)没有返回,因为她在付款表中没有任何记录。这取决于检查paid = 0的WHERE子句。

如果没有记录,我希望将0作为总和返回。

任何想法如何做到这一点?

3 个答案:

答案 0 :(得分:3)

将谓词payments.paid = 0WHERE移至ON子句,如:

SELECT users.*, SUM(payments.amount)
FROM users
LEFT JOIN payments
ON users.id = payments.user_id AND payments.paid = 0
GROUP BY users.id
ORDER BY users.id DESC

如果您将谓词放在WHERE条款中LEFT JOIN成为INNER JOIN

答案 1 :(得分:1)

你必须把 - > sum(isnull(payment.amount,0))作为查询中的付款计数

SELECT users.*, SUM(isnull(payments.amount,0))
FROM users
LEFT JOIN payments
ON users.id = payments.user_id
WHERE payments.paid = 0
GROUP BY users.id
ORDER BY users.id DESC

答案 2 :(得分:1)

试试这个: -

SELECT users.Id, users.name, SUM(case when paid=0 then amount else 0 end) as 
req_amt
FROM users
LEFT JOIN payments
ON users.id = payments.user_id
GROUP BY users.id,users.name
ORDER BY users.id DESC

感谢: - )