I’m building an AIR application and I’ve got a section which could benefit from the group_concat function.
I have a database with two tables:
CREATE TABLE pictures (
id INTEGER PRIMARY KEY AUTOINCREMENT,
author TEXT,
filename TEXT
)
and
CREATE TABLE tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT, fkPIcture INTEGER
)
Which have the following data:
INSERT INTO pictures (id,author,filename) VALUES (2,‘calvinshe’,‘5015892459_0a6baa53d4_m.jpg’);
INSERT INTO pictures (id,author,filename) VALUES (3,‘rfhsphoto’,‘5019232052_f6d9160fd2_m.jpg’);
INSERT INTO pictures (id,author,filename) VALUES (4,‘Stefnisson’,‘5019232080_2004d50a17_m.jpg’);
and
INSERT INTO tags (id,tag,fkPIcture) VALUES (6,‘sunset’,4);
INSERT INTO tags (id,tag,fkPIcture) VALUES (7,‘birds’,4);
INSERT INTO tags (id,tag,fkPIcture) VALUES (8,‘clouds’,4);
INSERT INTO tags (id,tag,fkPIcture) VALUES (9,‘bride’,2);
You can see that photo 4 has 3 tags, while photo 2 has just one tag. What I’d like to end up with is a record for each photograph in the pictures table, and a commadelimited list of tags for each photo. Basically like this:
author filename tags
Stefnisson 5019232080_2004d50a17_m.jpg sunset, birds, clouds
calvinshe 5015892459_0a6baa53d4_m.jpg bride
Now here’s the query I’ve got right now. It almost works, but for some reason it’s grouping the tags into the first photo’s record.
SELECT p.id, p.filename, p.author, p.photoURL, COALESCE(t.tags, “”) AS tags
FROM pictures p
LEFT JOIN (
SELECT fkPicture, GROUP_CONCAT(t.tag) as tags
FROM pictures p
LEFT JOIN tags t ON p.id = t.fkPicture
WHERE t.fkPicture = p.id
) t ON t.fkPicture = p.id
ORDER BY p.id DESC
I’m sure it has to do with the LEFT JOIN in the subquery, but I can’t figure it out. Is there someone who could help me take this the last 5%?