当row为空时,mysql返回多个0列

时间:2015-02-21 14:39:11

标签: mysql sql

我有这个复杂的查询,并没有按照我想要的方式工作,我希望有人可以帮助我。

SELECT 
 `username`, 
 `amount`, 
 `receipt`, 
 DATE_FORMAT(amount.time, '%e-%m-%Y') as paymentDate,
 SUM(CASE WHEN `our_result` = 'Y' THEN `difficulty` END) AS `accepted`,
 SUM(CASE WHEN `our_result` = 'N' THEN `difficulty` END) AS `rejected` 
FROM `shares`
JOIN ( 
 SELECT 
  amount, 
  time, 
  wallet, 
  receipt 
 FROM 
  userPayments 
 ORDER BY time DESC ) 
AS amount 
ON amount.wallet = shares.username 
WHERE `our_result` in ('Y','N') 
AND shares.time > DATE_SUB(now(), INTERVAL 1 HOUR) 
GROUP BY `username`

我的问题是,当userPayments表为空时,根本没有显示任何结果。我希望返回剩余的信息,即使userPayments表是空的,但无法弄清楚如何实现它。

非常感谢任何帮助。

感谢。

1 个答案:

答案 0 :(得分:0)

您必须使用LEFT OUTER JOIN(或LEFT JOIN),而不是JOIN

这意味着:

SELECT 
 `username`, 
 `amount`, 
 `receipt`, 
 DATE_FORMAT(amount.time, '%e-%m-%Y') as paymentDate,
 SUM(CASE WHEN `our_result` = 'Y' THEN `difficulty` END) AS `accepted`,
 SUM(CASE WHEN `our_result` = 'N' THEN `difficulty` END) AS `rejected` 
FROM `shares`
LEFT OUTER JOIN ( 
 SELECT 
  amount, 
  time, 
  wallet, 
  receipt 
 FROM 
  userPayments 
 ORDER BY time DESC ) 
AS amount 
ON amount.wallet = shares.username 
WHERE `our_result` in ('Y','N') 
AND shares.time > DATE_SUB(now(), INTERVAL 1 HOUR) 
GROUP BY `username`