加入多个条件的表格和更新列

时间:2015-06-30 21:22:56

标签: mysql

我有两个表customersorders,其中重要的列是:

/* Customers: */
id        | login     | membershipid
100       | email1    | 0
101       | email2    | 0

/* Orders: */
userid    | total
100       | 150
101       | 120
101       | 450

我想根据每位客户的总购买量更新membershipid。假设如果总和小于500则为零,如果总和为500-1000则为1,如果总和超过1000则为2。

我这样得到了总和:

SELECT customers.login, sum( orders.total ) AS total_purchased 
FROM xcart_customers AS customers
LEFT JOIN xcart_orders AS orders ON customers.id = orders.userid
GROUP BY customers.login

但我不知道如何更新客户表。类似的东西:

UPDATE xcart_customers set (membershipid) = (
    SELECT sum( orders.total ) AS total_purchased 
    FROM xcart_customers AS customers
    LEFT JOIN xcart_orders AS orders ON customers.id = orders.userid
    GROUP BY customers.login
)

但是在哪里以及如何使用条件(GROUP BY会有效吗?):

CASE 
    WHEN 
    ..
    ELSE 
END

2 个答案:

答案 0 :(得分:2)

UPDATE xcart_customers 
join
(
    SELECT customers.login, sum( orders.total ) AS total_purchased 
    FROM xcart_customers AS customers
    LEFT JOIN xcart_orders AS orders ON customers.id = orders.userid
    GROUP BY customers.login
) tmp on tmp.login = xcart_customers.login
set xcart_customers.membershipid = case when total_purchased is null or total_purchased < 500 then 0
                                        when total_purchased between 500 and 1000 then 1
                                        else 2
                                   end

答案 1 :(得分:1)

执行此操作的一种方法是使用连接操作。接受您的查询,并将其转换为内联视图,然后将其连接回customers表。

我们可能希望处理total_purchased为NULL时小于500的情况(当客户在xcart_orders中没有任何相关行时。)

作为SELECT,它看起来像这样:

SELECT t.login
     , t.membershipid
     , CASE 
         WHEN IFNULL(s.total_purchased,0) < 500 THEN 0
         WHEN s.total_purchased <= 1000 THEN 1
         WHEN s.total_purchased > 1000 THEN 2
         ELSE NULL
       END AS new_membershipid
  FROM customers t
  JOIN ( SELECT c.login
              , SUM(o.total) AS total_purchased 
           FROM xcart_customers c
           LEFT 
           JOIN xcart_orders o 
             ON o.userid = c.id 
          GROUP BY c.login
       ) s
    ON s.login = t.login

要将其转换为更新,请将SELECT ... FROM替换为UPDATE

并在语句末尾添加SET子句(如果有WHERE子句,则在WHERE子句之前)。

例如:

UPDATE customers t
  JOIN ( SELECT c.login
              , SUM(o.total) AS total_purchased 
           FROM xcart_customers c
           LEFT 
           JOIN xcart_orders o 
             ON o.userid = c.id 
          GROUP BY c.login
       ) s
    ON s.login = t.login
   SET t.membershipid =
       CASE 
         WHEN IFNULL(s.total_purchased,0) < 500 THEN 0
         WHEN s.total_purchased <= 1000 THEN 1
         WHEN s.total_purchased > 1000 THEN 2
         ELSE NULL
       END

注意:这假定customers表中的login是UNIQUE`。

<强>后续

鉴于memberid不能分配NULL值,我们可以调整CASE表达式。检查&gt;首先是1000,然后检查&gt; = 500,否则为0。

例如:

       CASE 
         WHEN s.total_purchased > 1000 THEN 2
         WHEN s.total_purchased >= 500 THEN 1
         ELSE 0
       END