【发布时间】:2020-10-07 14:34:32
【问题描述】:
您好,有这两张桌子:
#客户
cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email
'1000000001', 'Village Toys', '200 Maple Lane', 'Detroit', 'MI', '44444', 'USA', 'John Smith', 'sales@villagetoys.com'
'1000000002', 'Kids Place', '333 South Lake Drive', 'Columbus', 'OH', '43333', 'USA', 'Michelle Green', NULL
'1000000003', 'Fun4All', '1 Sunny Place', 'Muncie', 'IN', '42222', 'USA', 'Jim Jones', 'jjones@fun4all.com'
'1000000004', 'Fun4All', '829 Riverside Drive', 'Phoenix', 'AZ', '88888', 'USA', 'Denise L. Stephens', 'dstephens@fun4all.com'
'1000000005', 'The Toy Store', '4545 53rd Street', 'Chicago', 'IL', '54545', 'USA', 'Kim Howard', NULL
#Orders
order_num, order_date, cust_id
'20005', '2012-05-01 00:00:00', '1000000001'
'20006', '2012-01-12 00:00:00', '1000000003'
'20007', '2012-01-30 00:00:00', '1000000004'
'20008', '2012-02-03 00:00:00', '1000000005'
'20009', '2012-02-08 00:00:00', '1000000001'
现在,如果我在一个字段上使用子查询执行这个查询,称为订单:
SELECT cust_name,
cust_state,
(SELECT COUNT(*)
FROM Orders
WHERE Orders.cust_id = Customers.cust_id) AS orders
FROM Customers
ORDER BY cust_name;
我收到订单 0 的“Kids Place”:
cust_name, cust_state, orders
'Fun4All', 'IN', '1'
'Fun4All', 'AZ', '1'
'Kids Place', 'OH', '0'
'The Toy Store', 'IL', '1'
'Village Toys', 'MI', '2'
但如果我使用加入版:
SELECT c.cust_name,
c.cust_state,
COUNT(*) orders
FROM Customers c
INNER JOIN Orders o
ON o.cust_id = c.cust_id
GROUP BY o.cust_id
ORDER BY c.cust_name;
我没有得到“儿童场所”行:
cust_name, cust_state, orders
'Fun4All', 'IN', '1'
'Fun4All', 'AZ', '1'
'The Toy Store', 'IL', '1'
'Village Toys', 'MI', '2'
为什么我会出现这种行为?
【问题讨论】:
-
请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入作为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出尽可能少的代码,即您显示的代码可以通过您显示的代码扩展为不正常的代码。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)的 SQL,并以表格格式作为代码输入。 How to Ask 暂停总体目标的工作,将代码砍到第一个表达式,没有给出你所期望的,说出你所期望的以及为什么。
-
如果您没有说明为什么您期望得到您所期望的结果,并根据权威文档说明理由,那么您只是要求我们用定制的教程重写它,而不知道您的误解是什么。这还不够集中。