查询中的WHERE子句有2个连接和GROUPBY?

时间:2015-09-03 18:06:20

标签: mysql sql

我的目标是返回total balance大于4000.00的客户。我的问题:

SELECT c.cust_id AS 'customer ID',
       c.address AS 'address', 
       i.fname AS 'first name',
       i.lname AS 'last name',
       SUM(a.avail_balance) AS 'total balance'
  FROM customer c INNER JOIN individual i
  ON c.cust_id = i.cust_id
  INNER JOIN account a
  ON c.cust_id = a.cust_id
GROUP BY c.cust_id;

产生此结果

+---------------------+------------+-----------+---------------+
| address             | first name | last name | total balance |
+---------------------+------------+-----------+---------------+
| 47 Mockingbird Ln   | James      | Hadley    |       4557.75 |
| 372 Clearwater Blvd | Susan      | Tingley   |       2458.02 |
| 18 Jessup Rd        | Frank      | Tucker    |       3270.25 |
| 12 Buchanan Ln      | John       | Hayward   |       6788.98 |
| 2341 Main St        | Charles    | Frasier   |       2237.97 |
| 12 Blaylock Ln      | John       | Spencer   |      10122.37 |
| 29 Admiral Ln       | Margaret   | Young     |       5000.00 |
| 472 Freedom Rd      | Louis      | Blake     |       3875.18 |
| 29 Maple St         | Richard    | Farley    |      10971.22 |
+---------------------+------------+-----------+---------------+

但是我无法解决WHERE 'total balance' > 4000.00子句应该去的地方。据推测它必须在GROUP BY之后出现,但这对我编写它的方式不起作用。

2 个答案:

答案 0 :(得分:3)

试试这个:

SELECT c.cust_id AS 'customer ID',
       c.address AS 'address', 
       i.fname AS 'first name',
       i.lname AS 'last name',
       SUM(a.avail_balance) AS 'total balance'
  FROM customer c INNER JOIN individual i
  ON c.cust_id = i.cust_id
  INNER JOIN account a
  ON c.cust_id = a.cust_id
GROUP BY c.cust_id
HAVING SUM(a.avail_balance) > 4000;

答案 1 :(得分:1)

SELECT c.cust_id AS 'customer ID',
       c.address AS 'address', 
       i.fname AS 'first name',
       i.lname AS 'last name',
       SUM(a.avail_balance) AS 'total balance'
  FROM customer c INNER JOIN individual i
  ON c.cust_id = i.cust_id
  INNER JOIN account a
  ON c.cust_id = a.cust_id
GROUP BY c.cust_id
HAVING `total balance` > 4000;

您可以在HAVING查询中使用列别名,以避免进行第二次总结

来自文档(https://dev.mysql.com/doc/refman/5.0/en/select.html

  

HAVING子句几乎在最后一次应用,就在发送项目之前   对客户来说,没有优化。 (在HAVING之后应用LIMIT。)

     

HAVING子句可以引用a中指定的任何列或别名   SELECT列表或外部子查询中的select_expr,以及   集合函数。但是,SQL标准要求HAVING   必须仅引用GROUP BY子句中的列或使用的列   集合函数。同时适应标准SQL和   特定于MySQL的行为,能够引用SELECT中的列   列表,MySQL 5.0.2及以上允许HAVING引用中的列   SELECT列表,GROUP BY子句中的列,外部的列   子查询和聚合函数。