MySQL tiered query?

I have two tables (entries and tags) with a many-to-many link table. Right now, I am making a request to get all the records matching my criteria, and a request for each record to get the tags.

Is it possible to say that tags are returned through a new column as an array in the first query?

+3
source share
2 answers

This request:

SELECT     e.id                               entry_id
,          GROUP_CONCAT(t.txt ORDER BY t.txt) tags
FROM       entry e
LEFT JOIN  entry_tag et
ON         e.id = et.entry_id
LEFT JOIN  tag t
ON         et.tag_id = t.id
GROUP BY   e.id

Will return tags as a comma separated list. You can read additional parameters on GROUP_CONCAT: http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_group-concat

. , php explode: http://php.net/manual/en/function.explode.php

tag entry_tag, GROUP_CONCAT - (, JSON) GROUP_CONCAT , , :

$sql = '
    SELECT     e.id                  entry_id
    ,          t.id                  tag_id
    ,          t.txt                 tag_text
    ,          t.published           tag_published
    FROM       entry e
    LEFT JOIN  entry_tag et
    ON         e.id = et.entry_id
    LEFT JOIN  tag t
    ON         et.tag_id = t.id
    ORDER BY   e.id
';        
$result = mysql_query($ql);
$entry_id = NULL;
$entry_rows = NULL;
while ($row = mysql_fetch_assoc($result)) {
    if ($entry_id != $row['entry_id']) {
        if (isset($entry_id)) {           //ok, found new entry
            process_entry($entry_rows);   //process the rows collected so far
        }
        $entry_id = $row['entry_id'];
        $entry_rows = array();
    }
    $entry_rows[] = $row;                 //store row for his entry for later processing
}
if (isset($entry_id)){                    //process the batch of rows for the last entry
    process_entry($entry_rows);           
}
+1

Source: https://habr.com/ru/post/1733794/


All Articles