在我添加JOIN后,Postgresql查询无法正常工作

时间:2018-03-12 08:53:33

标签: sql postgresql

当我这样做一个查询时:

SELECT payment.customer_id, COUNT(payment.customer_id), SUM(payment.amount)
FROM payment 
GROUP BY customer_id
ORDER BY SUM(payment.amount) DESC
LIMIT 10

它完美无缺,但是当我尝试从另一个表中加入一个字段时,它会失败:

SELECT payment.customer_id, customer.email COUNT(payment.customer_id), SUM(payment.amount)
FROM payment 
GROUP BY customer_id
ORDER BY SUM(payment.amount) DESC
LIMIT 10
JOIN customer
ON payment.customer_id = customer.customer_id

我做错了什么?如何从客户表中添加电子邮件列?

2 个答案:

答案 0 :(得分:0)

要加入,您必须在From关键字之后使用它,如下面的

Select Table1.customer_id,Table1.email,Table1.amt from (
SELECT payment.customer_id, customer.email COUNT(payment.customer_id) email, SUM(payment.amount) amt
FROM payment 
GROUP BY customer_id
ORDER BY SUM(payment.amount) DESC
LIMIT 10
) Table1 JOIN customer
ON Table1.customer_id = customer.customer_id

答案 1 :(得分:0)

你错放了JOIN;它属于FROM子句。您的SELECT条款中也缺少逗号。

SELECT c.customer_id, c.email, COUNT(p.payment_id), SUM(p.amount)
FROM customer c
JOIN payment p ON p.customer_id = c.customer_id
GROUP BY c.customer_id
ORDER BY SUM(p.amount) DESC
LIMIT 10;

看到我在FROMJOIN中切换了表格。这不是必要的,但在我看来感觉好一点,说:给我的客户他们的付款数据。如果您希望客户没有付款数据,请切换到LEFT JOIN