如何写这个视图

时间:2011-12-27 19:24:06

标签: mysql sql

我有2张桌子

客户

customerid    
customername

订单

customerid
orderid
isopen [true/false]

如何创建包含以下内容的视图:

客户名称,总订单,总订单,其中isopen column == true

*更新**

create view CustomerOrders as
select c.id CustomerID, 
       max(c.customername) CustomerName,
       count(o.order_id) CustomerOrders,
       SUM(CASE WHEN o.isopen = 1 THEN 1 ELSE 0 END) AS OpenOrders
from customer c
left join orders o on c.id = o.customerid
group by c.id

谢谢大家 请更正你的答案,以便我能给你留下标记

5 个答案:

答案 0 :(得分:2)

尝试:

CREATE VIEW v1 AS 
  SELECT customername, count(orderid) as total_orders 
   FROM customer c
   LEFT JOIN orders o ON ( c.id = o.customerid AND o.isopen = TRUE)
  GROUP BY c.id

答案 1 :(得分:1)

尝试下面给出的语法

 Create View OpenOrders AS
       SELECT CUSTOMERNAME, count(ORDERID) FROM CUSTOMER INNER JOIN ORDERS
                CUSTOMER.CUSTOMERID = ORDERS.CUSTOMERID
       WHERE ORDERS.ISOPEN =1;

答案 2 :(得分:1)

尝试:

create view CustomerOrders as
select c.customerid CustomerID, 
       max(c.customername) CustomerName,
       count(o.order_id) CustomerOrders,
       SUM(CASE WHEN o.isopen = 1 THEN 1 ELSE 0 END) OpenOrders
from customer c
left join orders o on c.customerid = o.customerid
group by c.id

(假设您希望包含没有订单的客户 - 如果您只想包含订单的客户,请将左连接更改为内部联接。)

答案 3 :(得分:0)

你不能这样做,直到你有customerid属性和customername。他们不会联系其他

答案 4 :(得分:0)

这将是这样的,取决于表定义的细节(你没有提到):

create view viewname as
 select c.customername, count(o.*) as totalorders
  from customer c, orders o
   where c.customerid = o.customerid and o.isopen