0

I have two tables. voting_ip and country. I want to retrieve results from country table where open_id_fk (foreign key) of voting_ip table is equal to open_id(Primary Key) of country table. How to write sql query to combine these queries and return the result. I am using the below code in my codeigniter model to retrieve number of occurances of open_id_fk in voting_ip table.

public function mostvotedans()
{
    $this->db->select('open_id_fk, COUNT(*) as total');
    $this->db->group_by('open_id_fk'); 
    $this->db->order_by('total', 'desc'); 
    $query = $this->db->get('voting_ip', 5);
    return $query;

    $query = $this->db->query("SELECT * FROM country WHERE open_id_fk=open_id;");  
    return $query;         
}
1
  • use joins link Commented Aug 4, 2015 at 8:27

2 Answers 2

1

change it as following.

  public function mostvotedans()
{
  $this->db->select('c.open_id,COUNT(ip.open_id_fk) as total')->from('voting_ip ip');
  $this->db->join('country c','c.open_id=ip.open_id_fk');
  $this->db->group_by('ip.open_id_fk'); 
  $this->db->order_by('total', 'desc'); 
  $this->db->limit(5);
 $query = $this->db->get();
 return $query;


}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you.. this worked :) awesome.. i just modified it to get all the columns as.. $this->db->select('c.*,COUNT(ip.open_id_fk) as total')->from('voting_ip ip');
1

Use a join statement :

$query = $this->db->select('v.open_id_fk, COUNT(v.*) AS total, c.country_name')
            ->join('country AS c', 'c.open_id = v.open_id_fk')
            ->from('voting_ip AS v')
            ->group_by('v.open_id_fk')
            ->order_by('total', 'DESC')
            ->limit(5);

Should work, I put 'country_name' because I don't know your tables.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.