How to use sub query in INNER JOIN ON condition in zf2..? - php

I have to implement a condition in sql query where i need to use sub query in INNER JOIN ON condition as follows :
$select = new Select('booking');
$select->columns(array('*', new Expression("service_provider.first_name as sp_first_name, service_provider.last_name as sp_last_name,
invoice.status_id AS invoice_status,payment_history.currency as currency,CASE invoice.status_id WHEN 0 THEN 'Unpaid' WHEN 1 THEN 'Paid' WHEN 2 THEN 'Partially Paid' END AS PaymentStatus")));
$select->join('booking_suggestion_history', 'booking_suggestion_history.booking_id = booking.id AND booking_suggestion_history.id = (SELECT id FROM booking_suggestion_history WHERE booking_id = booking.id ORDER BY id DESC LIMIT 1)', 'inner');
$select->join('users', 'users.id = booking.user_id', array('first_name', 'last_name'), 'left');
$select->join(array('service_provider' => 'users'), 'service_provider.id = booking.service_provider_id', array(), 'left');
$select->join('service_provider_service', 'service_provider_service.id = booking.service_provider_service_id', array('duration', 'price'), 'left');
$select->join('service_category', 'service_category.id = service_provider_service.service_id', array('category_name'), 'left');
$select->join('invoice', 'invoice.id = booking.invoice_id', array('invoice_total', 'site_commision'), 'inner');
$select->join('invoice_details', 'invoice_details.invoice_id = invoice.id', array('sale_item_details'), 'inner');
$select->join('payment_history', 'payment_history.invoice_id = invoice.id', array(), 'inner');
$select->join('lookup_status', 'lookup_status.status_id = booking.status_id', array('status'), 'left');
query generating through these conditions (got through str_replace('"', '', $select->getSqlString());) is working fine in sql but zf2 throwing error :
Statement could not be executed (42000 - 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`id` `FROM` `booking_suggestion_history` `WHERE` `booking_id` = `booking`.`id` `' at line 2)
Please help..!!

Related

Order by not working with Group by in codeigniter

$loginuserID = $this->session->userdata("loginuserID");
$this->db->select('notice_x_user.*,notice.*,classes.*,sub_courses.*,,notice.status as studentStatus,notice.date as noticeDate');
$this->db->from('notice_x_user');
$this->db->join('notice','notice_x_user.noticeID = notice.noticeID', 'LEFT');
$this->db->join('classes', 'classes.ClassesID = notice.classesID', 'LEFT');
$this->db->join('sub_courses', 'sub_courses.sub_coursesID = notice.sub_coursesID', 'LEFT');
$wheres = "(notice_x_user.userID = '".$loginuserID."' and notice_x_user.usertype = 'Support') or notice.userID = '".$loginuserID."'";
$this->db->where($wheres);
$this->db->order_by('notice.noticeID', 'DESC');
$this->db->group_by('notice.noticeID');
I am join four table where I get correct data but the problem is that order by is not working while using group by. So, How can I do this? Please help me.
Thank You
use select_max for getting the max noticeID
$this->db->select('notice_x_user.*,notice.*,classes.*,sub_courses.*,,notice.status as studentStatus,notice.date as noticeDate');
$this->db->select_max('notice.noticeID' , 'noticeID');
$this->db->from('notice_x_user');
$this->db->join('notice','notice_x_user.noticeID = notice.noticeID', 'LEFT');
$this->db->join('classes', 'classes.ClassesID = notice.classesID', 'LEFT');
$this->db->join('sub_courses', 'sub_courses.sub_coursesID = notice.sub_coursesID', 'LEFT');
$wheres = "(notice_x_user.userID = '".$loginuserID."' and notice_x_user.usertype = 'Support') or notice.userID = '".$loginuserID."'";
$this->db->where($wheres);
$this->db->order_by('noticeID', 'DESC');
$this->db->group_by('notice.noticeID');
Grouping statements must be used before ordering statements, otherwise you'll get a MySQL error.
Just put the statements in the correct order:
$this->db->group_by('notice.noticeID');
$this->db->order_by('notice.noticeID', 'DESC');
and it'll work as expected

subquery treated as char in subquery codeigniter

I tried to use subquery in codeigniter to get the result and use the result as the parameter in where in clause. but i got this error.
and here is my codeigniter active record query:
$session['hasil'] = $this->session->userdata('logged_in');
$regional = $session['hasil']->regional;
$this->db->select('a.id_agency');
$this->db->from('tbl_agency a');
$this->db->join('tbl_collector_agency b', 'a.id_agency = b.id_agency', 'left');
$this->db->join('tbl_area_collector c', 'b.id_collector = c.id_collector', 'left');
$this->db->join('mysystem.lapkeu.dbo.groupbranch d', 'c.group_branch_id = d.GroupBranchID', 'left');
$this->db->where('d.regional', $regional);
$subQuery = $this->db->get_compiled_select();
$this->db->reset_query();
$this->db->select('*');
$this->db->from($this->table);
$this->db->where_in('id_agency', $subQuery);
im using microsoft sql server as my database.

Convert from query to ModelSearch of Yii2

I'm new in Yii2, and I have a query with right result:
SELECT DISTINCT workloadTeam.project_id, wp.project_name, workloadTeam.user_id, workloadTeam.commit_time, wp.workload_type FROM
(SELECT p.id, p.project_name, w.user_id, w.commit_time, w.comment, w.workload_type
FROM workload as w, project as p
WHERE w.user_id = 23 AND p.id = w.project_id) wp
INNER JOIN workload as workloadTeam ON wp.id = workloadTeam.project_id
But in my ModelSearch.php, I wrote:
$user_id = Yii::$app->user->id;
$subquery = Workload::find()->select('p.id', 'p.project_name', 'w.user_id', 'w.commit_time', 'w.comment', 'w.workload_type')
->from(['project as p', 'workload as w'])
->where(['user_id' => $user_id, 'p.id' => 'w.project_id']);
$query = Workload::find()
->select(['workloadTeam.project_id', 'wp.project_name', 'workloadTeam.user_id', 'workloadTeam.from_date', 'workloadTeam.to_date', 'workloadTeam.workload_type', 'workloadTeam.comment'])
->where(['', '', $subquery]);
$query->join('INNER JOIN', 'workload as workloadTeam', 'wp.id = workloadTeam.project_id');
It happended error:
SELECT COUNT(*) FROM `workload` INNER JOIN `workload` `workloadTeam` ON wp.id = workloadTeam.project_id WHERE `` (SELECT p.project_name `p`.`id` FROM `project` `p`, `workload` `w` WHERE (`user_id`=20) AND (`p`.`id`='w.project_id'))
And I can't fix it with right query above.
You have any solution about this?
Is this error shown in the Yii-debug toolbar? Then your query (which you mentioned as error) is probably only the count from the query which is listed before.
You missed to add the sub-query in from clause like you shown in your working sql. Add this in your where clause were just the wrong place. Put sub-queries in whereconditions, if you have scalar results, because you have to use this result with operands like =, >=, in...
This could work:
$user_id = Yii::$app->user->id;
$subquery = Workload::find()->select([
'p.id as id',
'p.project_name as project_name',
'w.user_id as user_id',
'w.commit_time as commit_time',
'w.comment as comment',
'w.workload_type as workload_type'
])
->from([
'project as p',
'workload as w'
])
->where([
'user_id' => $user_id,
'p.id' => 'w.project_id'
]);
$query = Workload::find()
->select([
'workloadTeam.project_id',
'wp.project_name',
'workloadTeam.user_id',
'workloadTeam.from_date',
'workloadTeam.to_date',
'workloadTeam.workload_type',
'workloadTeam.comment'
])
->from([$subquery => 'wp']); //you were missing this line
$query->join('INNER JOIN', 'workload as workloadTeam', 'wp.id = workloadTeam.project_id');
But you don't use any selects from your workload table in your main-query $query...
Since I don't know what's your goal to achieve I can't help you at this topic...

Error Number: 1066 Not unique table/alias: 'service' in codeigniter

Want to get all services in one to many relationship
My code is
$this->db->select('*');
$this->db->from('service');
$this->db->join('user', 'user.user_email = service.user_email', 'inner');
$this->db->join('service', 'service.user_email = user.user_email', 'inner');
$query = $this->db->get();
But it gives me an error
Error Number: 1066
Not unique table/alias: 'service'
SELECT * FROM (`service`) INNER JOIN `user` ON `user`.`user_email` = `service`.`user_email` INNER JOIN `service` ON `service`.`user_email` = `user`.`user_email`
Filename: C:\xampp\htdocs\service\system\database\DB_driver.php
If I do without
$this->db->from('service');
Then it gives syntax error
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN `user` ON `user`.`user_email` = `service`.`user_email` INNER JOIN `se' at line 2
SELECT * INNER JOIN `user` ON `user`.`user_email` = `service`.`user_email` INNER JOIN `service` ON `service`.`user_email` = `user`.`user_email`
Filename: C:\xampp\htdocs\service\system\database\DB_driver.php
You are trying to join the service table to the user table and then trying to join the service table again.
This isn't something you should generally be trying to do, and when you do it this way, the rendered SQL statement contains two attempts to reference the service table. It's the second JOIN that causes the database pain and it throws the error that you're seeing.
In this instance, just use:
$this->db->select('*');
$this->db->from('service');
$this->db->join('user', 'user.user_email = service.user_email', 'inner');
$query = $this->db->get();
Since the
$this->db->join('service', 'service.user_email = user.user_email', 'inner');
is redundant here (you've already joined these tables on that field.

How do sub-query in JOIN Codeigniter?

I tried to do sub-query SELECT in LEFT JOIN with an Active Records CI, but it gives an error:
near 'b.MedicalFacilitiesIdUser FROM medicalfacilities AS b WHERE b.MedicalFacilitiesI'
How as look, the query was distorted: b.MedicalFacilitiesI
Query is:
$this->db->join('stocks AS stn', 'stn.stocksIdMF =
(SELECT b.MedicalFacilitiesIdUser FROM medicalfacilities AS b
WHERE b.MedicalFacilitiesIdUser = stn.stocksIdMF AND stn.stocksEndDate >= UNIX_TIMESTAMP()
ORDER BY stn.stocksId DESC LIMIT 1)', 'LEFT');
Now full query is:
$this->db->select("MedicalFacilitiesName, MedicalFacilitiesAdres, MedicalFacilitiesDescription,
MedicalFacilitiesView, medicalfacilities.country, medicalfacilities.city, MedicalFacilitiesPhoto,
MedicalFacilitiesIdUser, idMedicalFacilities, id_specialization, id_MF, idUsers, UsersTypeAccount,
COUNT(commentstomedicalfacilities.idCommentsToMedicalFacilities) AS CNT,
COUNT(DISTINCT(stocks.stocksId)) AS count_stocks,
COUNT( su.idSubscrubeToUsers ) AS SBS,
coalesce(ROUND((SUM(ev.evaluationinstitutionEvalTotal) / SUM(ev.evaluationinstitutionEvalTotalRate))), 0) AS rate,
stocks.stocksName, stocks.stocksId, stocks.stocksEndDate, stocks.stocksStartDate,
typesmedicalfacilities.name AS nameType", FALSE);
$this->db->from('medicalfacilities');
$this->db->join('users', 'users.idUsers = medicalfacilities.MedicalFacilitiesIdUser');
$this->db->join('medicalfacilities_directions', 'medicalfacilities_directions.id_MF = medicalfacilities.MedicalFacilitiesIdUser', 'LEFT');
$this->db->join('subscrubetousers su', 'su.SubscrubeToUsersIdNote = medicalfacilities.MedicalFacilitiesIdUser AND su.SubscrubeToUsersType = 9', 'LEFT');
$this->db->join('thematicspecialization', 'thematicspecialization.idSpecialization = medicalfacilities_directions.id_specialization', 'LEFT');
$this->db->join('evaluationinstitution ev', 'ev.evaluationinstitutionIdInst = medicalfacilities.MedicalFacilitiesIdUser', 'LEFT');
$this->db->join('stocks', 'stocks.stocksIdMF = medicalfacilities.MedicalFacilitiesIdUser AND stocks.stocksEndDate >= UNIX_TIMESTAMP()', 'LEFT');
$this->db->join('commentstomedicalfacilities', 'commentstomedicalfacilities.CommentsToMedicalFacilitiesIdMedical = medicalfacilities.MedicalFacilitiesIdUser', 'LEFT');
$this->db->join('medicalfacilities_type', 'medicalfacilities_type.idMF = medicalfacilities.MedicalFacilitiesIdUser');
$this->db->join('typesmedicalfacilities', 'typesmedicalfacilities.type = medicalfacilities_type.type');
$this->db->join('stocks AS stn', 'stn.stocksIdMF = (SELECT b.MedicalFacilitiesIdUser FROM medicalfacilities AS b WHERE b.MedicalFacilitiesIdUser = stn.stocksIdMF AND stn.stocksEndDate >= UNIX_TIMESTAMP()
ORDER BY stn.stocksId DESC LIMIT 1)', 'LEFT');

Categories