Reputation: 71
I'm keep getting lost in this one and struggling to find the right method. Hopefully someone out there might know of a good way of doing what I want to do. I have two tables and I want to update one table using concatenated data from the other where the ids are the same. As an example....
Table1
ItemID CategoryID
1 20
1 30
1 40
2 10
3 40
3 20
4 10
4 20
Table2
ItemID CatIDs
1
2
3
4
I want to update Table2.CatIDs with all the Category IDs from Table1 where the ItemIDs match. It seems straightforward when I write it down like that but after trying Inner Joins, Sub Queries and so on as I've found online, I keep getting "You have errors in your SQL Syntax..."
I want Table2 to look something like
ItemID CatIDs
1 20,30,40
2 10
3 40,20
4 10,20
I've tried Inner Joins and also sub queries and the closest I've got without an error was this....
UPDATE Table2
SET Table2.CatIDs = Table2.CatIDs + ", " +
(SELECT CategoryID FROM Table1 WHERE Table2.ItemID = Table1.ItemID)
But it doesn't seem finished and all it done was update four rows with the same CatIDs and then give me the message #1242 - Subquery returns more than 1 row
I'm sure someone out there will be able to see where I'm going wrong and point me in the right direction.
Thanks in advance
Upvotes: 0
Views: 85
Reputation: 77876
Try like below by using group_concat()
you can get the ,
separated list and then join between the tables. But storing comma separated values is never a good idea.
update table2 t2
join
(
select ItemID,group_concat(CategoryID) as newcat
from table1 group by ItemID
) tab on t2.ItemID = tab.ItemID
set t2.CatIDs = tab.newcat
Upvotes: 0
Reputation: 1269813
You should realize that table1
is the right way to store this information. It is called a junction or association table. Sometimes you need to do the concatenation for presentation purposes, but you need to keep the junction table for full flexibility.
You can do what you want using an update
with join
and group by
:
UPDATE Table2 t2 JOIN
(SELECT t1.ItemId, GROUP_CONCAT(t1.CategoryId SEPARATOR ', ') as cats
FROM table1 t1
GROUP BY t1.ItemId
) tc
ON t2.ItemId = tc.ItemId
SET t2.CatIDs = tc.cats;
Upvotes: 1