编写子查询而不是加入MySQL

时间:2014-04-12 00:48:29

标签: mysql join subquery

这里我在a_bkorders数据库中有2个表。

mysql> select *
    -> from customers;
+---------+----------------+-----------------+------------+------------------+----------------`enter code here`
| cust_id | cust_name_last | cust_name_first | cust_state | cust_postal_code | 
+---------+----------------+-----------------+------------+------------------+----------------

mysql> select *
    -> from order_headers;
+----------+------------+---------+
| order_id | order_date | cust_id |
+----------+------------+---------+

我需要将cust_id,cust_name和订单数量(count(order_id)显示为'订单数),但是使用子查询,而不是连接。

这就是我写的:

SELECT cust_id, cust_name_last,'number of orders'
FROM 
    (
    SELECT cu.cust_id, cu.cust_name_last, count(oh.order_id) as 'number of orders'
    FROM a_bkorders.customers cu
    JOIN a_bkorders.order_headers oh ON cu.cust_id = oh.cust_id
    WHERE cu.cust_state in ('NJ', 'MA')
    ) A;

我得到了:

+---------+----------------+------------------+
| cust_id | cust_name_last | number of orders |
+---------+----------------+------------------+
|  208950 | Adams          | number of orders |
+---------+----------------+------------------+

但如果我单独运行子查询,我只能获得1行。 (我知道有很多)

+---------+----------------+------------------+
| cust_id | cust_name_last | number of orders |
+---------+----------------+------------------+
|  208950 | Adams          |               70 |
+---------+----------------+------------------+

所以我的问题是为什么单独的子查询只会吐出一行而不是多行。另外,我是否使用子查询正确加入了两个表,为什么在运行整个查询时会得到number of orders

提前感谢您的帮助,

嘀嘀

1 个答案:

答案 0 :(得分:1)

您希望在查询中纠正的内容很少

  • 在子查询中,为count变量提供一个明确的别名,而不是'order of orders'和
  • 使用该别名作为要显示的列名称(将名称命名为您想要显示的内容)
  • 最重要的是使用group by子句来获得所需的结果(您使用的是聚合计数)

以下是修改过的查询

SELECT cust_id, cust_name_last, count as 'number of orders'
FROM 
(
SELECT cu.cust_id, cu.cust_name_last, count(oh.order_id) as count
FROM a_bkorders.customers cu
JOIN a_bkorders.order_headers oh ON cu.cust_id = oh.cust_id
WHERE cu.cust_state in ('NJ', 'MA')
GROUP BY oh.cust_id
) A;

希望这有帮助!