简体   繁体   中英

Select sql from 3 tables one to many

Hello guys I have a question, My database has 3 tables

tags(id,name);

articles(id,title,smallimage,date,views);

tags_in_news(id,news_id,tag_id);

Now I want all article.titles attached to a tag.
I tried this but didn't help much: My function:

public function get($obj_id)
{
    $this->load->database();
    $news = $this->db->query("SELECT 
                              t.name,
                              t.id,
                              a.title,
                              a.date,
                              a.views,
                              a.smallimage,
                              tin.id,
                              group_concat(a.title)
                              from tags_in_news tin
                              inner join tags t on t.id = tin.tag_id
                              inner join articles a on a.id = tin.news_id
                              and t.id = ?
                              group by t.id",array($obj_id));
    if ($news->num_rows())
    {
        $news = $news->result_array();
    }   
    else
    {
        $news = NULL;
    }

    return $news;
}
Array
(
[0] => Array
    (
        [name] => new tag
        [id] => 57
        [group_concat(a.title,a.views)] => Article1 52,Article3 51,Article3 56
    )

)

All articles attached to a tag:

SELECT 
t.name tag,GROUP_CONCAT(DISTINCT a.title) titles
FROM tags_in_news tin
INNER JOIN tags t ON t.id = tin.tag_id
INNER JOIN articles a ON a.id = tin.news_id
GROUP BY t.id;

One thing to note here is default length allowed for GROUP_CONCAT is 1024 chars.
So its recommended to get ids(if you suspect your concated value could go beyond the limit) as comma separated values and once you get ids you can do point queries afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM