Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL group_concat problem
    primarykey
    data
    text
    <p>Greetings,</p> <p>I have a very tricky problem with the <strong>group_concat</strong> function and I'm thinking for some days with no success, how to solve it.</p> <p>There are 3 tables:</p> <pre><code>tasks task_tag tag +---------+----------+ +---------+----------+ +---------+----------+ | task_id | data | | task_id | tag_id | | tag_id | name | +---------+----------+ +---------+----------+ +---------+----------+ | 1 | task 1 | | 1 | 5 | | 5 | work | | 2 | task 2 | | 1 | 7 | | 6 | school | | 3 | task 3 | | 2 | 6 | | 7 | home | +---------+----------+ +---------+----------+ +---------+----------+ </code></pre> <p>When all tasks need to be retrieved, with all tags that they are associated with as a result column, there is no problem with the following query:</p> <pre><code>SELECT t.task_id, t.data, GROUP_CONCAT(tg.name) AS tags FROM tasks t LEFT JOIN task_tag tt ON tt.task_id = t.task_id LEFT JOIN tag tg ON tg.tag_id = tt.tag_id GROUP BY t.task_id result +---------+-----------+-------------+ | task_id | data | tags | +---------+-----------+-------------+ | 1 | task 1 | work,home | | 2 | task 2 | school | | 3 | task 3 | NULL | +---------+-----------+-------------+ </code></pre> <p>The problem is when I need to select the tasks from one EXACT tag, but I still need to preserve the tags column with all of the tasks' associated tags. I try with the following query, but since the result is limited by WHERE tag_id = 5, the group_concat function retrieves just the tag with id = 5, e.g. "work":</p> <pre><code>SELECT t.task_id, t.data, GROUP_CONCAT(tg.name) AS tags FROM tasks t LEFT JOIN task_tag tt ON tt.task_id = t.task_id LEFT JOIN tag tg ON tg.tag_id = tt.tag_id WHERE tg.tag_id = 5 GROUP BY t.task_id result +---------+-----------+-------------+ | task_id | data | tags | +---------+-----------+-------------+ | 1 | task 1 | work | +---------+-----------+-------------+ </code></pre> <p>The result that I'm trying to achieve is:</p> <pre><code>result +---------+-----------+-------------+ | task_id | data | tags | +---------+-----------+-------------+ | 1 | task 1 | work,home | +---------+-----------+-------------+ </code></pre> <p>Thank you very much for any suggestions on how to resolve this!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload