Codeigniter join repeats returned values

▼魔方 西西 提交于 2020-01-05 08:43:28

问题


Okay first sorry if its a stupid question but im a really big beginner.

I have 3 database tables, videos, events, and users.

My problem is if i join these 3 tables and showing the results in my view it duplicates.

For example if i echo out the users name in my profile , and i uploaded 7 videos it shows the name seven times.

function get_profile($id) 
    {
        $this->db->select('*');
        $this->db->from('pf_users');
        $this->db->join('pf_videos', 'pf_videos.uid = pf_users.uid');
        $this->db->join('pf_events', 'pf_events.uid = pf_users.uid');
        $this->db->where('pf_users.uid', $id);
        $q = $this->db->get();
        if($q->num_rows() > 0)
        {
            foreach($q->result() as $row)
            {
                $data[] = $row;
            }

            return $data;
        }   
            else 
        {
            show_404();
        }

}

i even repeats the menus

<ul class="profile_menu">
        <?php foreach ($results as $res): ?>
            <li><a href="#" class="profile_info">Információ</a></li>
            <li><a href="#" class="profile_event">Eseményei (<?php echo count($res->title) ?>)</a></li>
            <li><a href="#" class="profile_photos">Party képei (0)</a></li>
            <li><a href="#" class="profile_video">Videói (<?php echo count($res->url); ?></a></li>
        <?php endforeach; ?>

could please someone point out what i am missing? and sorry if its a stupid question.

thank you


回答1:


It is normal that you will have duplicate content as you are missing the group by statement. In your situation you need to add:

$this->db->group_by("pf_users.uid");

Now you have both joint pf_videos and pf_events and the normal thing is to have duplicate content as you have both information about pf_events and pf_videos . If you though don't need both information a simple DISTINCT will do the job for you, so you can simply have

 $this->db->select('DISTINCT pf_users.*',false);

without using the group_by statement. To learn more about DISTINCT and GROUP BY you can simply read the following links:

http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html



来源:https://stackoverflow.com/questions/9748460/codeigniter-join-repeats-returned-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!