有一张 table ,上面有 ID、Items、Coffee、Brewer、Tea、Milk
已经从其他表中提取了 ID 和 Items,我可以使用案例语句使用 Items 列将 Item_1 更新为 4
输出看起来
ID Item_ID Items Coffee Brewer Tea Milk
1 101 Coffee 1 0 0 0
1 102 Brewer 0 1 0 0
2 103 Tea 0 0 1 0
3 104 Milk 0 0 0 1
必需的输出:我想根据 ID 得到 1,比如第一条两条记录有 coffee 和 Brewer 都应该包含 1
ID Item_ID Items Coffee Brewer Tea Milk
1 101 Coffee 1 1 0 0 /* Note Brewer value*/
1 102 Brewer 1 1 0 0
2 103 Tea 0 0 1 0
3 104 Milk 0 0 0 1
查询
insert into All_Items select distinct ID, Item_ID, Items from temp;
Update All_Items
SET coffee = case
when Items = 'Coffee' Then '1' else '0' end,
Brewer= case
when Items = 'Brewer' Then '1' else '0' end,
Tea= case
when Items = 'Tea' Then '1' else '0' end,
Milk= case
when Items = 'Milk' Then '1' else '0' end;
最佳答案
这可能对你有帮助:
Update All_Items
set coffee = case when Items = 'Coffee' Or id in (select * from (select id from All_Items where items = 'Coffee')t) Then '1' else '0' end,
Brewer= case when Items = 'Brewer' Or id in (select * from (select id from All_Items where items = 'Brewer')t) Then '1' else '0' end,
Tea= case when Items = 'Tea' Or id in (select * from (select id from All_Items where items = 'Tea')t) Then '1' else '0' end,
Milk= case when Items = 'Milk' Or id in (select * from (select id from All_Items where items = 'Milk')t) Then '1' else '0' end;
编辑:
你可以得到两张 table ,然后像这样制作你的 table :
所有项目表
itemID Coffee Brewer Tea Milk
1 1 1 0 0
2 0 0 1 0
3 0 0 0 1
项目表
ID Item_ID
1 101
1 102
2 103
3 104
WHERE All_Items.itemID = items.ID
像这样你可以通过将 1 设置为 item_id 的特定列来轻松更新你的表
关于MySQL:要合并的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23251417/