如何解决大型数据库从联接表中查找倒数第二个修改结果的“超时”错误?

时间:2019-04-29 08:59:42

标签: php mysql codeigniter

我有3个MySQL Tables用户,面板和引脚。用户表大约有66列。针表有89列,板表有12列。一个用户表拥有近35,000个用户,pin拥有0.3百万条记录,而board则有7k个board。一个用户可以有多个板,一个板可以包含多个引脚。我需要每个用户的最后修改的部分,以便如果很长一段时间没有更新,我可以向他们发送电子邮件。

我已经在codeigniter中尝试了以下代码。

$this->db->select("t1.id as pin_id, t1.id, t1.user_id, `t1.title`,t1.image, t1.description, t1.profession_tag, t1.industry_tag, t1.collaborators, `t2.title` as board_title, t3.email, t3.username, t3.firstname");
        $this->db->from("pin as t1");
        $this->db->join('board as t2', 't1.board_id = t2.id', 'left');
        $this->db->join('user as t3', 't1.user_id = t3.id', 'left');
        $this->db->where('t3.status', 1);
        $this->db->where('t3.hidden_profile', 1);
        $this->db->where('t1.status', 1);
        $this->db->group_by('t1.user_id');
        $this->db->limit($limit, $start);
        $query = $this->db->get();
        return $query->result_array();

但是,如果用户有超过1000个图钉,则需要花费很多时间。请提出我可以做些什么来改善它并更快地得到结果。我也没有得到查询的最后修改结果。我不知道它如何与Haveing子句一起工作。

1 个答案:

答案 0 :(得分:0)

以下是一个建议。在Join语句中使用子查询。参见Trendfischer的answerAn Essential Guide to MySQL Derived Table

$this->db->select("t1.id as pin_id, t1.id, t1.user_id, `t1.title`,t1.image, t1.description, t1.profession_tag, t1.industry_tag, t1.collaborators, `t2.title` as board_title, t3.email, t3.username, t3.firstname");
$this->db->from("pin as t1");
$this->db->join('(SELECT id, title FROM board) AS t2', 't1.board_id = t2.id', 'left');
$this->db->join('(SELECT id, email, username, firstname FROM user status = 1 AND hidden_profile = 1) AS t3', 't1.user_id = t3.id', 'left');
$this->db->where('t1.status', 1);
$this->db->group_by('t1.user_id');
$this->db->limit($limit, $start);
$query = $this->db->get();
return $query->result_array();