我有1個表稱爲樣本,它有3列。Mysql更新查詢示例表
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查詢? 感謝
我有1個表稱爲樣本,它有3列。Mysql更新查詢示例表
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查詢? 感謝
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
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;
這應該工作。
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;
http://stackoverflow.com/questions/3154911/sql-server-update-a-column-if-row-is-the-first-record-in-group –