我想更新表格但需要按商店名称分组。我希望所有具有相同商店名称的分组条目都使用相同的ID进行更新。所有其他商店都应该有自己的身份证。
这就是我的尝试:
SET @row_number:=0;
UPDATE `TABLE 75` as t1
INNER JOIN (SELECT search_shop FROM `TABLE 75` WHERE sap_id = '' GROUP BY search_shop) as t2
ON t1.search_shop = t2.search_shop
SET sap_id = CONCAT('XX',@row_number:=@row_number+1)
使用此查询,每个条目都获得一个自己的ID - 即使是具有相同名称的ID。
所以我想要这样的事情:
shop_name - sap_id
sm_name_1 - XX1
sm_name_2 - XX2
sm_name_2 - XX2
sm_name_3 - XX3
等等。
提前感谢您的帮助! :)
答案 0 :(得分:1)
CREATE TABLE t
(`shop_name` varchar(9), `sap_id` varchar(3))
;
INSERT INTO t
(`shop_name`, `sap_id`)
VALUES
('sm_name_1', ''),
('sm_name_2', 'XX2'),
('sm_name_2', ''),
('sm_name_3', 'XX3'),
('sm_name_3', ''),
('sm_name_4', ''),
('sm_name_5', '')
;
update t
inner join (
select
t.shop_name
, CONCAT('XX', @rn := if(@prev = shop_name, @rn, @rn + 1)) as sap_id
, @prev := shop_name
from
t
, (select @prev := null, @rn := 0) var_init
order by shop_name
)sq on t.shop_name = sq.shop_name
set t.sap_id = sq.sap_id;
select * from t;
| SHOP_NAME | SAP_ID |
|-----------|--------|
| sm_name_1 | XX1 |
| sm_name_2 | XX2 |
| sm_name_2 | XX2 |
| sm_name_3 | XX3 |
| sm_name_3 | XX3 |
| sm_name_4 | XX4 |
| sm_name_5 | XX5 |