If I have a table:
CREATE TABLE Kids (
kid_id int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
kid_name varchar(45) NOT NULL,
kid_favcolors (text) NULL,
PRIMARY_KEY(kid_id)
)
and I have a table:
CREATE TABLE Colors (
color_id int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
color_name varchar(45) NOT NULL,
PRIMARY_KEY(color_id)
)
With rows that reference favorite colors via comma separated ids:
INSERT INTO Kids(kid_name, kid_favcolors) VALUES('Joe','1,2,3,4,5');
INSERT INTO Kids(kid_name, kid_favcolors) VALUES('Mary','1,2,3');
How would I create a statement that would return each entry in the Kid database with the Kid_name and the color_name of all of the ids referenced in the kid_favcolors column.
For example:
COLORS:
color_id color_name 1 yellow 2 green 3 blue 4 purple 5 red 6 brown 7 black
KIDS:
kid_id kid_name kid_favcolors 1 Joe 1,2,3,4,5 2 Mary 1,2,3
and I want to retrieve
kid_id kid_name favorite_colors 1 Joe yellow, green, blue, purple, red 2 Mary yellow, green, blue
The queries are being executed on existing data and database structure. If there is no feasible solution, rearranging the structure of the data is possible but I assume would add a considerable amount of time to the solution. Either way, would like some help.
I am able to retrieve the colors from the database using:
SELECT STUFF((SELECT ', ' + color_name FROM colors WHERE color_id IN (1,2,3,4,5) FOR XML PATH('')),1, 2, '') AS colors
colors
1 yellow, green, blue, purple, red
But when I try a more complex query I can’t seem to find a way to incorporate the above statement by pulling the ids from the Kids table.
SELECT kids.kid_id, kids.kid_name, favorite_colors FROM kids JOIN colors ON colors.id IN kids.kid_favcolors as favorite_colors
While it looks like it could work to me, not working. Not sure if I’m way off or really close.
I have worked up a solution; though it’s not pretty, it works.
I have talked to them about reworking the DB and implementing a current administration site to accommodate the changes
Split String function I used: