【问题标题】:Codeigniter: Complex query for 2 tablesCodeigniter:2个表的复杂查询
【发布时间】:2014-12-27 19:59:21
【问题描述】:

我有 2 张桌子:

events     event_follows
-------    -------------
id         id
title      user_id
content    event_id
user_id  

我需要获取某个 user_id 的所有事件、事件计数、获取该用户关注的所有事件并获取所有事件和关注的计数。真的,我不知道如何在 1 个查询中正确执行此操作。

【问题讨论】:

  • $this->db->get_where('event_follows', array('used_id' => $user_id)); 然后你去$this->db->get_where('events', array('user_id' => $user_id); 然后解析它
  • 您的预期 O/P plzz??

标签: php mysql codeigniter select join


【解决方案1】:

从你的问题中我可以理解,我只能想到这个解决方案:

$query = "select e.*, count(e.*), ef.*, count(ef.*) from events e join event_follows ef on ef.user_id = e.user_id where e.user_id = '$my_id' ";
$data['info'] = $this->db->query($query)->result_array();

//Then, you can use php's echo "<pre>", print_r() and die() functions 
//to test the result:

echo "<pre>";
print_r(data['info']);
die();

【讨论】:

    【解决方案2】:

    我已经做了一些解决方案。但不幸的是,它比 1 个查询更复杂:

        // Fetch all events which was joined by user
        $this->db->select('event_id')
                 ->from('event_follows')
                 ->where('user_id', $id);
    
        $query1 = $this->db->get(); 
        $result = $query1->result_array();   
    
        // Drop keys
        $joined_events = array();       
        foreach($result as $row)
        {
            array_push($joined_events, $row["event_id"]);   
        }
    
        // Fetch all events
        $this->db->select('events.*, COUNT(event_follows.id) as followers')
                 ->from('events')
                 ->where('events.user_id', $id)
                 ->or_where_in('events.id', $joined_events);
        $this->db->join('event_follows', 'event_follows.event_id = events.id', 'left')
                 ->group_by('event_follows.event_id');
    
        $query2 = $this->db->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 2023-03-24
      • 2012-08-07
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      相关资源
      最近更新 更多