0

我有 1 个名为 sample 的表,它有 3 列。

id   customer   default_address

1     1         0   
2     1                 0

3     1         0   
4     1         0   
5     2         0   
6     2         0   
7     3         0   
8     3         0   
9     2         0

10    2         0

在这里,我想按客户分组并更新第一个默认地址应为 1,并为每个客户其余全部为 0。如何进行mysql查询?谢谢

4

3 回答 3

1
UPDATE  tb a
        LEFT JOIN
        (
            SELECT  customer, MIN(id) id
            FROM    tb
            GROUP   BY customer
        ) b ON a.customer = b.customer AND
                a.ID = b.ID
SET     a.default_address = b.ID IS NOT NULL
于 2013-10-26T08:11:27.833 回答
0
Update Table1 
INNER JOIN (Select Min(`id`) as MinID,`customer`
From Table1 Group by `customer`) t2
SET Table1.`default_address` = 1
WHERE Table1.`id` = t2.MinID;

样品小提琴

于 2013-10-26T08:18:33.673 回答
0
UPDATE sample 
  LEFT JOIN 
  (SELECT MIN(id) id,customer 
   FROM sample 
   GROUP BY customer) t ON sample.customer=t.customer 
SET default_address="1" 
WHERE sample.id=t.id;

这应该有效。

于 2013-10-26T08:14:33.720 回答