JOIN THREE TABLES IN CODEIGNITER - php

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

Related

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...

MYSQL: echo out results from table but don't echo out duplicate results?

I am really struggling with this so hope someone can help. I have a table like so:
id | msg_id | to_user_id | from_user_id | subject | content
1 1 6 10 hi hello
2 1 6 10 hi hello
3 1 10 6 hi hello
4 2 4 1 hi
5 3 1 4 hi
i am wanting to echo out the results of this table with the below query using mysql.
At the moment i am getting all the results echoed out fine, but i do not want to echo out duplicate results. In this instance the number '1' appears in the column 'msg_id' four times. I want to use DISTINCT COUNT or something similar to select all the rows from 'msg_id' but to not echo out the duplicates and only count '1' once.
here's my mysql statement:
function get_inbox2() {
global $connection;
global $_SESSION;
$query = "SELECT *
FROM ptb_messages m, ptb_profiles p
WHERE m.to_user_id =".$_SESSION['user_id']."
AND m.to_user_deleted !='".$_SESSION['user_id']."'
AND m.from_user_deleted !='".$_SESSION['user_id']."'
AND m.from_user_id != '0'
AND p.user_id = m.from_user_id
ORDER BY m.date_sent DESC";
$inbox_set2 = mysql_query($query, $connection);
confirm_query($inbox_set2);
return $inbox_set2;
}
I have tried something like this but it's not showing the results:
$query = "SELECT COUNT(DISTINCT msg_id) totalCOUNT FROM ptb_messages WHERE to_user_id=".$_SESSION['user_id']."";
Try getting only the msg_id with MAX(id) (you can either get the MIN with the same logic) for each id:
SELECT m.*,p.*
FROM ptb_messages m
INNER JOIN ptb_profiles p ON p.user_id = m.from_user_id
INNER JOIN (
SELECT MAX(id) AS id,msg_id
FROM messages
GROUP BY msg_id
) a ON a.id = m.id
WHERE m.to_user_id = ".$_SESSION['user_id']."
AND m.to_user_deleted != '".$_SESSION[' user_id ']."'
AND m.from_user_deleted != '".$_SESSION[' user_id ']."'
AND m.from_user_id != '0'
ORDER BY m.date_sent DESC

Mysql query ( LINK tickets, employee , cats , comments ) using JOIN

here is my tables
Tickets
tic_id,
tic_cat
tic_priority
tic_cus
tic_date
tic_title
tic_msg
tic_files
tic_emp
tic_moved
tic_statue
tic_rate
Employee
emp_id
emp_name
emp_username
emp_password
emp_cat
emp_special
emp_lastlogin
emp_session
emp_code
emp_statue
emp_master
emp_ip
Cats
cat_id
cat_type
cat_name
cat_statue
cat_delete
cat_date
cat_ip
cat_options
Comments
com_id
tic_id
cus_id
emp_id
com_msg
com_time
com_ip
com_statue
And I need the result as
tic_id | tic_cat | cat_name | tic_title | tic_statue | tic_priority | tic_msg | emp_name | comments_row | last_comment |
I Make this query but i have 2 problems
Query Is
SELECT
tickets.tic_id
,tickets.tic_cat
,cats.cat_name
,tickets.tic_title
,tic_statue
,tic_priority
,tickets.tic_msg
,employee.emp_name
,count(comments.com_id)
,( SELECT comments.com_msg
from comments
order by com_id DESC limit 1 )
AS last_comment
FROM tickets
LEFT JOIN employee
on (tickets.tic_emp = employee.emp_id)
LEFT join cats
on (tickets.tic_cat = cats.cat_id)
LEFT JOIN comments
on(tickets.tic_id = comments.tic_id)
WHERE tic_cus=2 /* 2 -> This Is Customer Id */
GROUP BY comments.tic_id
My Problems Is
i have 3 Result In Database To Customer Number 2 -> only show 2 results
i want to get Last Comment -> the 2 Result have the same last comment
How Can i do this Query With Out This 2 Errors
Edit The Post After New Query
Problem number Two Solved Using This Query
SELECT
tickets.tic_id
,tickets.tic_cat
,cats.cat_name
,tickets.tic_title
,tic_statue
,tic_priority
,tickets.tic_msg
,employee.emp_name
,count(comments.com_id)
,( SELECT comments.com_msg
from comments
WHERE tickets.tic_id = comments.tic_id
order by com_id DESC limit 1 )
AS last_comment
FROM tickets
LEFT JOIN employee
on (tickets.tic_emp = employee.emp_id)
LEFT join cats
on (tickets.tic_cat = cats.cat_id)
LEFT JOIN comments
on(tickets.tic_id = comments.tic_id)
WHERE tic_cus=2
GROUP BY comments.tic_id
Solved
SELECT
tickets.tic_id
,tickets.tic_cat
,cats.cat_name
,tickets.tic_title
,tic_statue
,tic_priority
,tickets.tic_msg
,employee.emp_name
,count(comments.com_id)
,( SELECT comments.com_msg
from comments
WHERE tickets.tic_id = comments.tic_id
order by com_id DESC limit 1 )
AS last_comment
FROM tickets
LEFT JOIN employee
on (tickets.tic_emp = employee.emp_id)
LEFT join cats
on (tickets.tic_cat = cats.cat_id)
LEFT JOIN comments
on(tickets.tic_id = comments.tic_id)
WHERE tic_cus=2
GROUP BY tickets.tic_id
1) Can you show some data in these tables to demonstrate? In other words, how do you know you should have three records? Does select * from tickets where tic_cus = 2 by itself return 3 records?
2) You need to filter the comments subquery by ticket. I would also recommend having the comment count in a subquery as well and leave out the GROUP BY altogether:
,( select count(comments.com_id)
from comments
where comments.tic_id = tickets.tic_id) as comment_count
,( select comments.com_msg
from comments
where comments.tic_id = tickets.tic_id
^^^^^^^ filter by ticket so not last of ALL comments
order by com_id DESC limit 1) as last_comment

How do I join 4 tables on mysql select statement?

I have 4 tables in MySQL to join. Example
$select = $db->query("SELECT *
FROM ads
WHERE ad_pic='1'
AND ad_status = '1'
ORDER BY ad_id DESC LIMIT 0,4");
while ($fetch = $db->fetch($select)) {
$iquery = $db->query("SELECT *
FROM images
WHERE img_ads_id = '" . intval($fetch['ad_id']) . "'
AND img_status = '1'
LIMIT 1");
$thumb = $db->fetch($iquery);
$uselect = $db->query("SELECT *
FROM users
WHERE user_id = '".intval($fetch['ad_userid'])."'
AND user_status = '1'
LIMIT 1");
$ufetch = $db->fetch($uselect);
$cselect = $db->query("SELECT *
FROM category
WHERE cat_slug = '".safe_func($fetch['ad_category'])."'
LIMIT 1");
$cfetch = $db->fetch($cselect);
}
I want to know the way to join these in one select statement.
ads table
ad_id ad_userid ad_category
-------------------------------
1 2 5
images table
img_id img_ads_id
-------------------------------
1 1
users table
user_id user_name
-------------------------------
2 John
category table
cat_id cat_name
-------------------------------
5 Vehicles
SELECT *
FROM ads AS a
LEFT JOIN images AS i ON i.img_ads_id = a.ad_id AND i.img_status = 1
LEFT JOIN users AS u ON u.id = a.ad_userid AND u.user_status = 1
LEFT JOIN category AS c ON c.cat_slug = a.ad_category
WHERE a.ad_pic = 1
AND a.ad_status = 1
ORDER BY a.ad_id DESC
LIMIT 0,4
If an ad must have an image, user, or category, you may use a JOIN instead of a LEFT JOIN. If an ad can have more than one image, user, or category, you will need a more complex query.

How to specify the parent query field from within a subquery in MySQL?

How do I specify the parent query field from within a subquery in MySQL?
For Example:
I have written a basic Bulletin Board type program in PHP.
In the database each post contains: id(PK) and parent_id(the id of the parent post). If the post is itself a parent, then its parent_id is set to 0.
I am trying to write a mySQL query that will find every parent post and the number of children that the parent has.
$query = "SELECT id, (
SELECT COUNT(1)
FROM post_table
WHERE parent_id = id
) as num_children
FROM post_table
WHERE parent_id = 0";
The tricky part is that the first id doesn't know that it should be referring to the second id that is outside of the subquery. I know that I can do SELECT id AS id_tmp and then refer to it inside the subquery, but then if I want to also return the id and keep "id" as the column name, then I'd have to do a query that returns me 2 columns with the same data (which seems messy to me)
$query = "SELECT id, id AS id_tmp,
(SELECT COUNT(1)
FROM post_table
WHERE parent_id = id_tmp) as num_children
FROM post_table
WHERE parent_id = 0";
The messy way works fine, but I feel an opportunity to learn something here so I thought I'd post the question.
How about:
$query = "SELECT p1.id,
(SELECT COUNT(1)
FROM post_table p2
WHERE p2.parent_id = p1.id) as num_children
FROM post_table p1
WHERE p1.parent_id = 0";
or if you put an alias on the p1.id, you might say:
$query = "SELECT p1.id as p1_id,
(SELECT COUNT(1)
FROM post_table p2
WHERE p2.parent_id = p1.id) as num_children
FROM post_table p1
WHERE p1.parent_id = 0";
You could try something like this
SELECT pt.id,
CountTable.Cnt
FROM post_table pt LEFT JOIN
(
SELECT parent_id,
COUNT(1) Cnt
FROM post_table
WHERE parent_id <> 0
GROUP BY parent_id
) CountTable ON pt.id = CountTable.parent_id
WHERE pt.parent_id = 0
To get back to your example, use the alias of the main table in the sub select
SELECT pt.id,
(SELECT COUNT(1) FROM post_table WHERE parent_id = pt.id)
FROM post_table pt
WHERE pt.parent_id = 0
Give the tables unique names:
$query = "SELECT a.id, (SELECT COUNT(1) FROM post_table b WHERE parent_id = a.id) as num_children FROM post_table a WHERE a.parent_id = 0";
The following syntax works in Oracle. Can you test if the same works in MYSQL too?
It is called scalar subquery in Oracle.
You would just need to alias the two tables differently to distinguish between them if you are using the same table twice.
sql> select empno,
2 (select dname from dept where deptno = emp.deptno) dname
3 from emp
4 where empno = 7369;
EMPNO DNAME
---------- --------------
7369 RESEARCH
sql> select parent.empno,
2 (select mgr from emp where empno = parent.empno) mgr
3 from emp parent
4 where empno = 7876;
EMPNO MGR
---------- ----------
7876 7788
Thanks Don. I had a nested query as shown below and a WHERE clause in it wasn't able to determine alias v1. Here is the code which isn't working:
Select
teamid,
teamname
FROM
team as t1
INNER JOIN (
SELECT
venue_id,
venue_scores,
venue_name
FROM venue
WHERE venue_scores = (
SELECT
MAX(venue_scores)
FROM venue as v2
WHERE v2.venue_id = v1.venue_id /* this where clause wasn't working */
) as v1 /* v1 alias already present here */
);
So, I just added the alias v1 again inside the JOIN. Which made it work.
Select
teamid,
teamname
FROM
team as t1
INNER JOIN (
SELECT
venue_id,
venue_scores,
venue_name
FROM venue as v1 /* added alias v1 here again */
WHERE venue_scores = (
SELECT
MAX(venue_scores)
FROM venue as v2
WHERE v2.venue_id = v1.venue_id /* Now this works!! */
) as v1 /* v1 alias already present here */
);
Hope this will be helpful for someone.
Parent query field within a subquery in MySQL 8.
I'm selecing games scores on the basis of username from tblgamescores using nested query.
SELECT
GameScoresID,
(SELECT Username FROM tblaccounts WHERE AccountID = FromAccountID) AS FromUsername,
(SELECT Username FROM tblaccounts WHERE AccountID = ToAccountID) AS ToUsername,
(SELECT Username FROM tblaccounts WHERE AccountID = WinAccountID) AS WinUsername,
(SELECT Username FROM tblaccounts WHERE AccountID = LossAccountID) AS LossUsername,
FromUserScore,
ToUserScore
FROM tblgamescores a
WHERE FromAccountID = (SELECT AccountID FROM tblaccounts WHERE Username = "MHamzaRajput");

Categories