Multiple Select Count SQL queries in Codeigniter Active Record - php

I like to convert following MySQL queries into Codeigniter Active Record Queries.
Following is MySQL:
select brand_id,name,(select count(*) from items where brand_id = b.brand_id) as itemc, (select count(*) from models where brand_id = b.brand_id) as modelc from brands as b
Codeigniter :
$this->db->limit($perpage,$page);
$query = 'select brand_id,name,(select count(*) from items where brand_id = b.brand_id) as itemc, (select count(*) from models where brand_id = b.brand_id) as modelc from brands as b limit '.$perpage.' offset '.$page.'';
$query = $this->db->query($query);
$query = $query->result();
return $query;
Kindly help me to get the above codes converted for Codeigniter Active Record.

here is the query in active records
$rows = $this->db->select('b.brand_id,b.name')
->select('(select count(*) from items where brand_id = b.brand_id) as itemc',FALSE)
->select('(select count(*) from models where brand_id = b.brand_id) as modelc',FALSE)
->from('brands as b')
->limit($perpage,$page)->get()->result();

Related

JOIN THREE TABLES IN CODEIGNITER

I have three tables
1.article (id,article_title)
2.article_status(id,article_id,stage_id)
3.article_stages(id,stage_name)
Each article have multiple insertion in table 2. I want to fetch the last value which indicate the current stage using join query
article
id article_title
1 article1
2 article2
article_status
id article_id stage_id
1 1 1
2 1 2
3 1 3
4 2 1
article_stages
id stage_name
1 Stage1
2 Stage2
3 Stage3
I need the result like
id article_title stage_name
1 article1 Stage3
2 article2 Stage1
Here is my query
"SELECT `article`.`article_title` as id,`article`.`article_title`,`article_stages`.`stage_name`, MAX(`article_status`.`stage_id`) AS stage_id FROM (`article`)
JOIN `article_status` ON `article_status`.`article_id`=`article`.`id`
JOIN `article_stages` ON `article_stages`.`id` = (SELECT MAX(`stage_id`) FROM `article_status` )
GROUP BY `article_status`.`article_id`"
I tried this
public function getAllArticleforIssue($condition = array())
{
$table1 = 'article';
$table2 = 'article_status';
$table3 ='article_stages';
$this->db->select($table1.'.id as id,'.$table1.'.article_title,'.$table3.'.stage_name');
$this->db->select_max($table2.'.stage_id');
$this->db->from('rsgp_article');
$this->db->join($table2,$table2.'.article_id='.$table1.'.id');
$this->db->join($table3 , $table3.'.id = '.$table2.'.stage_id');
if (count($condition) > 0)
$this->db->where($condition);
$this->db->group_by($table2.".article_id");
$query = $this->db->get();
return $query->result_array();
}
Query Explanation:
Find article_id and current_stage_id ( see subquery groupedTable)
join with article and article_stages table in order to get
description.
SQL:
select article_id, article_title, stage_name
from ( select article_id , max(stage_id) as current_Stage_ID
from article_status
group by article_id ) groupedTable
join article on article.id = groupedTable.article_id
join article_stages on article_stages.id = groupedTable.current_Stage_ID
PHP:
function function_name() {
$sql = "select article_id, article_title, stage_name
from ( select article_id , max(stage_id) as current_Stage_ID
from article_status
group by article_id ) groupedTable join article on article.id = groupedTable.article_id
join article_stages on article_stages.id = groupedTable.current_Stage_ID";
$query = $this -> db -> query($sql);
$result = $query -> result_array();
return $result;
}
Use this query
SELECT a.article_title,s.stage_name
FROM article a
JOIN (
SELECT MAX(stage_id) max_id, article_id
FROM article_status
GROUP BY article_id
) b ON (b.article_id = a.article_id)
JOIN article_stages s ON (s.id = b.max_id)
try this query
$this->db->select('a.id, a.article_title, c.stage_name');
$this->db->from('article a');
$this->db->join('article_status b','b.article_id=a.id','left');
$this->db->join('article_stage c','c.id=b.article_status', 'left');
$this->db->group_by('a.article_name');
$this->db->get()->result_array();
You can use this query
SELECT a.id,a.artcle_title,s.stage_name
FROM article a
JOIN (
SELECT MAX(stage_id) max_id, article_id
FROM article_status
GROUP BY article_id
) b ON (b.article_id = a.id)
JOIN article_stages s ON (s.id = b.max_id)
With ID Column...
modified answer of - #Roshan Dandgavhal

How to write select query to get all child id by parent id in mysqli

I am trying to get all child ids by parent id from a single table.
Below is my table course:
Here is my code:
public function getLeftMenuMainCategoryInfoFromDb()
{
$sqlQuery = "SELECT p.course_id AS parent_id ,p.course_name As parent_coursename ,c.course_id AS child_id ,c.course_name As child_coursename FROM course As p LEFT JOIN course As c ON c.course_parent_id = p.course_id WHERE p.course_parent_id = 0 ORDER BY p.course_id";
$result = $this->selectQuery($sqlQuery);
//print_r($result);
return $result;
}
I think are you looking for Parent ID should be GROUP BY
SELECT p.*,
q.course_name
FROM course p
INNER JOIN
(SELECT course_id,
course_name
FROM course
WHERE course_parent_id = 0
ORDER BY course_id) q ON p.course_parent_id = q.course_id
GROUP BY p.course_parent_id;
Try this Query SELECT GROUP_CONCAT(course_id),course_parent_id FROM courseGROUP BY course_parent_id
SELECT GROUP_CONCAT(course_id),course_parent_id FROM course WHERE course_parent_id =1 GROUP BY course_parent_id
IF this is not you want please elaborate your question.

SQL in php force WHERE IN to find more than one time the same id

I am trying to to do a cart where the products have customizations... To avoid lot of queries in the data base I have tried to save the results in an array after the query. The query looks like this:
$sql = 'SELECT *
FROM cc_restaurants_menu
WHERE menu_id
IN ("7","50","50")
ORDER BY FIELD (menu_id,"7","50","50")';
$result = $conn->query($sql);
if($result->rowCount() > 0) {
while($row = $result->fetch()) {
$names[] = $row['menu_product'] .'<br>';
}
}
But the problem with this is that the query avoid the repeated ids. (I need repeated ids because the people can add the product more than one time).
Is there anyway to get the repeated ids more than one time?
The only idea I have is do something like (if the ids are in an array) :
foreach($ids as $d) {
//query here the database based in each id
}
thanks in advance
Think you might need one query for each menu_id, and use UNION ALL to join the results together.
Something like this:-
SELECT *
FROM cc_restaurants_menu
WHERE menu_id = "7"
UNION ALL
SELECT *
FROM cc_restaurants_menu
WHERE menu_id = "50"
UNION ALL
SELECT *
FROM cc_restaurants_menu
WHERE menu_id = "50"
ORDER BY FIELD (menu_id,"7","50","50")
Or build up the required menu ids in a sub query which you then join against the main table.
SELECT cc_restaurants_menu.*
FROM cc_restaurants_menu
INNER JOIN
(
SELECT 7 AS a_menu_id UNION ALL SELECT 50 UNION ALL SELECT 50
) sub0
ON cc_restaurants_menu.menu_id = sub0.a_menu_id
ORDER BY FIELD (cc_restaurants_menu.menu_id,"7","50","50")
Generating the first query with implode would be done something like this:-
$sql = "SELECT * FROM cc_restaurants_menu WHERE menu_id = '".implode("' UNION ALL SELECT * FROM cc_restaurants_menu WHERE menu_id = '", id_array)."' ORDER BY FIELD (menu_id,'".implode("','", id_array)."')";
and generating the 2nd query with implode would be done something like this:-
$sql = "SELECT cc_restaurants_menu.* FROM cc_restaurants_menu INNER JOIN (SELECT ".implode(" AS a_menu_id UNION ALL SELECT ", id_array) AS a_menu_id ) sub0 ON cc_restaurants_menu.menu_id = sub0.a_menu_id ORDER BY FIELD (cc_restaurants_menu.menu_id,".implode(",", id_array).")";

MySQL count from intermediary table

I'm trying to find the most used categories in an intermediary table which contains two ids, I'm running this to find all the counts of posts against categories.
$data = $conn->query('SELECT * FROM category WHERE category_name ORDER BY category_name');
foreach($data as $row) {
$sql = "SELECT COUNT(p_id) FROM p_categories c,category ca WHERE c.category_id = ca.category_id AND category_name = :category_name";
$q = $conn->prepare($sql);
$q->execute(array(':category_name' => $row['category_name']));
$catco = $q->fetch();
echo '<p>'.$row['category_name'].' ('.$catco[0].')</p>';
}
This returns all the categories, but I want to limit it to only the top four categories having most p_id. I tried limiting the count query to 4 but that didn't work.
Here are the tables:
posts: p_id, p_name
p_categories: p_id, category_id
category: category_id, category_name
You can do this in a single query
$sql = "SELECT p_categories.category_id, COUNT(*) AS cnt, category.category_name
FROM p_categories
LEFT JOIN category
ON p_categories.category_id = category.id
GROUP BY `category_id`
ORDER BY cnt
DESC LIMIT 4"
$data = $conn->query($sql);
foreach($data as $row) {
echo '<p>'.$row['category_name'].' ('.$row['cnt'] .')</p>';
}

Codeigniter using three queries in one functions

i have three tables
Users :
id
username
password
Second table
Friends
id
myid
friends_id
and last one
CI_Sessions
session_id
User_id = default =0
User_data
i want Codeignier Query
select * from users where userid=$userid
select * from friends where myid=$userid or friend_id=$userid
select * from ci_sessions where user_id=$userid and user_data!=''
return result()
is possible to get all three in one statement ?
i was trying like this
function check_friends($username) {
$this->db->where('username',$username);
$q1 = $this->db->get('users');
$myid=$q1->row('userid');
if($username !='' ){
$this->db->select('*');
$this->db->from('users');// I use aliasing make joins easier
$this->db->where('userid',$myid);
$this->db->join('myfriends AS friends_tpl', 'friends_tpl.myid = '.$myid.' or friends_tpl.fid='.$myid.'', 'FULL');
$this->db->join('ci_sessions AS B', 'B.id_unite = A.userid', 'INNER');
$this->db->where('B.user_data !=','');
$this->db->where('B.id_unite !=','0');
$query = $this->db->get();
return $query->result();
}else{
}
}
Update
i try this query
$query = $this->db->query("select * from users as u inner join myfriends as f on f.fid = '".$this->session->userdata('userid')."' or f.myid= '".$this->session->userdata('userid')."' inner join ci_sessions as c on c.id_unite = u.userid where u.username != '$username' GROUP BY u.userid ");
but there is problem , this query not correct result as i want ,
this is friends table value
id | myid | friend_id
1 | 50 | 54
2 | 57 | 50
now if three users login , the query will show that user 54 is friend with user 57 i don't know w7y
Do like this
$query = $this->db->query( 'SELECT * -----
UNION ALL
SELECT * -----
UNION ALL
SELECT *---' );
this will give all result...

Categories