MySQL:要合并的查询

标签 mysql

有一张 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;

DEMO HERE

编辑:

你可以得到两张 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/

相关文章:

mysql - 在 MySQL 中存储 BINARY 的优点

php - MySQL INDEX Varchar Field 500 for urls

mysql - 如何获取过滤后的列表

php - 网站内容如何存储?

mysql - 从表中删除后自动递增

mysql - 2个不同表中webmatrix中的动态sql查询

mysql - 声明变量时出现错误#1064

mysql - 2 个外键链接消息中的发送者和接收者

PHP - 进阶 MYSQL 同时

mysql - 为什么当等效的 SELECT 有效时,此 DELETE 查询会失败?