2014-04-12 20 views
0

这里我在a_bkorders数据库中有2个表。写入子查询而不是联接MySQL

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和顺序()作为订单的“数计数(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

感谢您对您的帮助提前,

迪迪

+0

重命名'数量的订单'后,您在SQL中选择它,你不能这样做。它会返回您选择的名称的名称。 – Shang

+0

你的意思是这样的:选择CUST_ID,cust_name_last, '的订单数' FROM \t( \t SELECT cu.cust_id,cu.cust_name_last,计数(oh.order_id) \t FROM a_bkorders.customers铜 \t JOIN a_bkorders.order_headers oh ON cu.cust_id = oh.cust_id \t WHERE cu.cust_state in('NJ','MA') \t)A; ?它仍然显示“订单数量” –

+0

,这是因为您尝试双击选择cust_id和cust_name_last的位置。如果你这样做 SELECT'订单数量'FROM(SELECT cu.cust_id,cu.cust_name_last,count(oh.order_id)FROM a_bkorders.customers cu JOIN a_bkorders.order_headers oh cu.cust_id = oh.cust_id WHERE cu.cust_state in ('NJ','MA'))A;这是你想要的吗? – Shang

回答

1

有你想在您的查询

  • 在子查询改正,给予了明确的别名几件事计数变量而不是'订单数量'
  • 使用该别名作为要显示的列名称(将别名命名为您要显示的名称)
  • 最重要的使用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; 

希望这有助于!