查询返回多行

时间:2014-08-31 21:32:22

标签: mysql sql database subquery

我试图从Sakila示例数据库中获取每个客户的总租金金额 所以我尝试了以下查询:

select customer.customer_id, customer.first_name, 
(select sum(payment.amount) from customer
inner join rental on customer.customer_id=rental.customer_id
inner join payment on rental.rental_id=payment.rental_id group by payment.amount) 
from customer
inner join rental on customer.customer_id=rental.customer_id
inner join payment on rental.rental_id=payment.rental_id
group by customer.customer_id;

我得到了这个" Subquery返回多行"。你知道什么可能是错的吗?谢谢

2 个答案:

答案 0 :(得分:2)

这是您的查询,包括一些重新格式化和表别名的使用:

select c.customer_id, c.first_name, 
      (select sum(p2.amount)
       from customer ce inner join
            rental r2
            on c2.customer_id = r2.customer_id inner join
            payment p2
            on r2.rental_id = p2.rental_id
       group by p2.amount
-------^
      ) 
from customer c inner join
     rental r
     on c.customer_id = r.customer_id inner join
     payment p
     on r.rental_id = p.rental_id
group by c.customer_id;

我已经强调了问题的具体原因。但修复方法是从根本上简化查询:

select c.customer_id, c.first_name, sum(p.amount)
from customer c left join
     rental r
     on c.customer_id = r.customer_id left join
     payment p
     on r.rental_id = p.rental_id
group by c.customer_id;

答案 1 :(得分:1)

这是您正在寻找的结果吗?

SELECT C.customer_id
    ,C.first_name
    ,SUM(P.amount) AS [total_amount]
FROM customer C
INNER JOIN rental R ON R.customer_id = C.customer_id
INNER JOIN payment P ON P.rental_id = R.rental_id
GROUP BY C.customer_id, C.first_name
-- Condition to get only the largest amount
-- without using an ORDER BY clause
HAVING SUM(P.amount) = (SELECT MAX(SUM(P2.amount))
                                           FROM rental R2
                                           INNER JOIN payment P2 ON P2.rental_id = R2.rental_id
                                           GROUP BY R2.customer_id)

希望这会对你有所帮助。