我正在学习MySQL。我想了解更多有关子查询的OUTER JOIN的信息。所以这意味着我不想使用CASE和IF
所以现在我有两张看起来像这样的表。
带有c_id和c_name的 customer
表,带有order_id,c_id,order_type的order
表。 order_type只有三种值,'a','b','c'
现在我想做一个显示客户订单明细的摘要。
该表应如下所示
c_name a b c
person1 1 0 2
person2 0 1 2
person3 0 0 0
这是我到目前为止所拥有的
SELECT c.c_id, COUNT(A), COUNT(B) , COUNT(C)
FROM customer as c
LEFT OUTER JOIN (
SELECT c_id, order_type as A FROM order
WHERE order_type = 'a')
AS first
ON first.c_id = c.c_id
LEFT OUTER JOIN (
SELECT c_id, order_type as B FROM order
WHERE order_type = 'b')
AS second
ON second.c_id = c.c_id
LEFT OUTER JOIN (
SELECT c_id, order_type as C FROM order
WHERE order_type = 'c')
AS third
ON third.c_id = c.c_id
group by c_name