左前生成每個Item_Number
值的總和左表聯接返回行,並在左邊的表的每一行,在右邊的表中的所有匹配的行。
因此,例如:
create table Customers (name varchar(50));
insert Customers values
('Tim'),
('John'),
('Spike');
create table Orders (customer_name varchar(50), product varchar(50));
insert Orders values (
('Tim', 'Guitar'),
('John', 'Drums'),
('John', 'Trumpet');
create table Addresses (customer_name varchar(50), address varchar(50));
insert Addresses values (
('Tim', 'Penny Lane 1'),
('John', 'Abbey Road 1'),
('John', 'Abbey Road 2');
然後,如果你運行:
select c.name
, count(o.product) as Products
, count(a.address) as Addresses
from Customers c
left join Orders o on o.customer_name = c.name
left join Addresses a on a.customer_name = c.name
group by name
你得到:
name Products Addresses
Tim 1 1
John 4 4
Spike 0 0
但約翰沒有4級的產品!
如果沒有group by
運行,你可以看到爲什麼計數是關閉:
select *
from Customers c
left join Orders o on o.customer_name = c.name
left join Addresses a on a.customer_name = c.name
你得到:
name customer_name product customer_name address
Tim Tim Guitar Tim Penny Lane 1
John John Drums John Abbey Road 1
John John Drums John Abbey Road 2
John John Trumpet John Abbey Road 1
John John Trumpet John Abbey Road 2
Spike NULL NULL NULL NULL
正如你所看到的,加入最終重複對方。對於每個產品,重複地址列表。這給你錯誤的數字。爲了解決這個問題,使用優秀的其他答案之一:
select c.name
, o.order_count
, a.address_count
from Customers c
left join
(
select customer_name
, count(*) as order_count
from Orders
group by
customer_name
) o
on o.customer_name = c.name
left join
(
select customer_name
, count(*) as address_count
from Addresses
group by
customer_name
) a
on a.customer_name = c.name
子查詢確保只有一行每個客戶加入。結果好多了:
name order_count address_count
Tim 1 1
John 2 2
Spike NULL NULL
finnaly解決我的問題:)謝謝先生! – 2013-02-25 14:00:40