如何更新包含逗号分隔值的表行?

时间:2012-12-14 05:52:36

标签: mysql

我有2张桌子第1张桌子包含姓名,电子邮件,vegetable_Fruits和饮料

CREATE TABLE Likes
(
Name varchar(20),
email varchar(20),
Vegetables_Fruits varchar(20),
Drinks varchar(20)
) 

我正在存储蔬菜,水果和饮料等人的姓名和电子邮件 一个人可以拥有任何一个价值 如果一个人喜欢蔬菜我将更新表格

name email 1 0

如果一个人喜欢水果,那么

name email 2 0

如果一个人喜欢饮料,那么

name email 0 1

插入查询

INSERT INTO Likes(Name,email,Vegetables_Fruits,Drinks)
     VALUES("aaa","aaa@example.com",1,0),("bbb","bbb@example.com",2,0),("ccc","cc@example.com",0,1),("ddd","dd@example.com",2,0),("eee","ee@example.com",2,0),("fff","ff@example.com",1,0),("ggg","gg@example.com",0,1),("hhh","hh@example.com",0,1) 

我有另一张包含电子邮件列表的表

CREATE TABLE emailList
(
Likes_Vegetables varchar(50),
Likes_Fruits varchar(50),
Drinks varchar(50)
)

插入查询

INSERT INTO emailList(Likes_Vegetables,Likes_Fruits,Drinks)
       VALUES("aaa@example.com,ff@example.com","bbb@example.com,dd@example.com,'ee@example.com'","hh@example.com,gg@example.com,cc@example.com")

我想根据1st table(Likes)的值更新第二个表(emailList) 这个

的查询是什么

3 个答案:

答案 0 :(得分:2)

update emailList 
set 
Likes_vegetables=(select Group_concat(email) from LIKES where Vegetables_Fruits=1),
Likes_Fruits=(select Group_concat(email) from LIKES where Vegetables_Fruits=2),
Drinks=(select Group_concat(email) from LIKES where Drinks=1)

答案 1 :(得分:1)

我认为您正在搜索group_concat,也许这样查询

INSERT INTO emailList(Likes_Vegetables,Likes_Fruits,Drinks)
      values ( (SELECT GROUP_CONCAT(email) FROM Likes WHERE Vegetables_Fruits=1) , (SELECT GROUP_CONCAT(email) FROM Likes WHERE Vegetables_Fruits=2) , (SELECT GROUP_CONCAT(email) FROM Likes WHERE Vegetables_Fruits=0) )

答案 2 :(得分:-1)

这可以解决你的问题 -

  

更新emailList设置Likes_Vegetables =   的concat(Likes_Vegetables “aaa@example.com”),                        Likes_Fruits = concat(Likes_Fruits,“ee@example.com”),                        Drinks = concat(Drinks,“cc @ example.com”);