jeudi 14 janvier 2016

Group_Concat with many-to-many table, keep non matching records

I have a database with 3 tables: articles, tags, and a junction table. A tag can be set for multiple records, and a record can have multiple tags.

I want to get all the articles with all their associated tags, like:

Article
ID | Article   | Title
1  | article 1 | About wifi
2  | article 2 | About bluetooth
3  | article 3 | About firewire

Tag
ID | Tag
1  | tag1
2  | tag2
3  | tag3

Article_Tag
Article_ID | Tag_ID
1          | 1
1          | 2
1          | 3
2          | 1

Wanted result:
article 1  | About wifi       | tag1; tag2; tag3
article 2  | About bluetooth  | tag1; 
article 3  | About firewire   | 

I fount the perfect solution in this fiddle http://ift.tt/1mYZJwK, but unfortunately it is for MySQL. I need SQLite and am not able to translate it. The analogy to the fiddle is that the articles are a person and the tags are mails.

I have been up to here:

SELECT _a.a_id, 
       _a.name, 
       _a.detail, 
       IFNULL(GROUP_CONCAT(DISTINCT _b.email,', '), '') mails
FROM a _a
    LEFT OUTER JOIN ab _ab 
        JOIN b _b 
            ON (_ab.b_id = _b.b_id)
        ON (_ab.a_id = _a.a_id)
GROUP BY _a.a_id ASC;

But it gets an error somewhere near ON.

I also tried this

SELECT 
    _a.a_id,
    _a.name,
    _a.detail,
    IFNULL(GROUP_CONCAT(_b.email,';'),'')
FROM a AS _a
LEFT OUTER JOIN ab AS _ab     
     ON _a.a_id = _ab.a_id
LEFT OUTER JOIN b AS _b     
     ON _b.b_id = _ab.b_id

which only returns one record: article 3, but with all tags concatenated.

Aucun commentaire:

Enregistrer un commentaire