Laravel & MySQL having a join on a join? - mysql

I need to join a table on a already joined table cause the data I need from the other table is also spread in another table. This is my SQL model so far:
Now I need to join the addresses table the joined child table as well cause I need the address of each child as well. My only problem is, how can I join the table addresses based on the childs.address_id?
I have already tried to to this:
INNER JOIN `addresses` AS `addresse_child` ON `childs`.`address_id` = `addresses`.`id`
Sadly not working..
My SQL Query so far (DB::getQueryLog())
SELECT `assignments`.`id` AS `assignment_id`,
`assignments`.`persons` AS `assignment_persons`,
`assignments`.`start_date` AS `assignment_start_date`,
`assignments`.`end_date` AS `assignment_end_date`,
`addresses`.`id` AS `address_id`,
`addresses`.`first_name` AS `address_first_name`,
`addresses`.`last_name` AS `address_last_name`,
`addresses`.`company` AS `address_company`,
`childs`.`id` AS `child_id`,
`childs`.`address_id` AS `child_address_id`,
`childs`.`sibling_id` AS `child_sibling_id`,
`childs`.`height` AS `child_height`,
`childs`.`weight` AS `child_weight`
FROM `assignments`
INNER JOIN `addresses` ON `assignments`.`address_id` = `addresses`.`id`
INNER JOIN `childs` ON `assignments`.`id` = `childs`.`assignment_id`
WHERE `assignments`.`deleted_at` IS NULL
AND `addresses`.`deleted_at` IS NULL
AND `childs`.`deleted_at` IS NULL
My Laravel SQL command:
$assignment_data = DB::table('assignments')
->join('addresses', 'assignments.address_id', '=', 'addresses.id')
->join('childs', 'assignments.id', '=', 'childs.assignment_id')
->select(
'assignments.id as assignment_id',
'assignments.persons as assignment_persons',
'assignments.start_date as assignment_start_date',
'assignments.end_date as assignment_end_date',
'addresses.id as address_id',
'addresses.first_name as address_first_name',
'addresses.last_name as address_last_name',
'addresses.company as address_company',
'childs.id as child_id',
'childs.address_id as child_address_id',
'childs.sibling_id as child_sibling_id',
'childs.height as child_height',
'childs.weight as child_weight'
)
->whereNull('assignments.deleted_at')
->whereNull('addresses.deleted_at')
->whereNull('childs.deleted_at')
->get();

You should be able to do;
SELECT `assignments`.`id` AS `assignment_id`,
`assignments`.`persons` AS `assignment_persons`,
`assignments`.`start_date` AS `assignment_start_date`,
`assignments`.`end_date` AS `assignment_end_date`,
`addresses`.`id` AS `address_id`,
`addresses`.`first_name` AS `address_first_name`,
`addresses`.`last_name` AS `address_last_name`,
`addresses`.`company` AS `address_company`,
`childs`.`id` AS `child_id`,
`childs`.`address_id` AS `child_address_id`,
`childs`.`sibling_id` AS `child_sibling_id`,
`childs`.`height` AS `child_height`,
`childs`.`weight` AS `child_weight`
FROM `assignments`
INNER JOIN `addresses` ON `assignments`.`address_id` = `addresses`.`id`
INNER JOIN `childs` ON `assignments`.`id` = `childs`.`assignment_id` AND
`childs`.`address_id` = `addresses`.`id`
WHERE `assignments`.`deleted_at` IS NULL
AND `addresses`.`deleted_at` IS NULL
AND `childs`.`deleted_at` IS NULL
And in Laravel this can be achieved by doing;
$assignment_data = DB::table('assignments')
->join('addresses', 'assignments.address_id', '=', 'addresses.id')
->join('childs', function($q) {
$q->on('assignments.id', '=', 'childs.assignment_id')
->where('childs.address_id', '=', 'addresses.id');
})
->select(
'assignments.id as assignment_id',
'assignments.persons as assignment_persons',
'assignments.start_date as assignment_start_date',
'assignments.end_date as assignment_end_date',
'addresses.id as address_id',
'addresses.first_name as address_first_name',
'addresses.last_name as address_last_name',
'addresses.company as address_company',
'childs.id as child_id',
'childs.address_id as child_address_id',
'childs.sibling_id as child_sibling_id',
'childs.height as child_height',
'childs.weight as child_weight'
)
->whereNull('assignments.deleted_at')
->whereNull('addresses.deleted_at')
->whereNull('childs.deleted_at')
->get();
However you should note that by doing INNER JOINS you will only get results if there are rows in each table. You maybe better off doing LEFT JOINS instead, depending on how your data is required.

Related

How to use "MAX" in codeigniter where?

There is $this->db_selec_max(); for select max element from row set in select but I want to use max in where. How to use "MAX" in codeigniter where? I want to convert following query in to codeigniter form
My query
SELECT rq_id, rq_plant_4sale_code, rq_serial_number, rq_quantity_requested, rq_requester_farm_id,
rq_fulfiller_farm_id, rqpri_description, rqrem_remark,rqrem_remark_datetime, rq_created_datetime,
plsal_name_botanical, plsal_name_english, pot_code, rqpri_description
FROM (reqn_requisitions)
LEFT JOIN reqn_requisition_priorities ON(rq_priority_rank=rqpri_rank)
LEFT JOIN reqn_requisition_remarks ON(rq_id=rqrem_reqn_id)
LEFT JOIN tukai_plants_4sale ON(rq_plant_4sale_code=plsal_id)
LEFT JOIN tukai_pots ON(plsal_pot_id=pot_id)
WHERE rqrem_remark_datetime IN(SELECT MAX(rqrem_remark_datetime) AS dt FROM reqn_requisition_remarks GROUP BY rqrem_reqn_id ) AND rq_challan_id=0'
I am trying like this
$this->db->select("rq_id, rq_plant_4sale_code, rq_serial_number, rq_quantity_requested, rq_requester_farm_id,
rq_fulfiller_farm_id, rqpri_description, rqrem_remark,rqrem_remark_datetime, rq_created_datetime,
plsal_name_botanical, plsal_name_english, pot_code, rqpri_description ");
$this->db->join('tukai_plants_4sale',
'tukai_plants_4sale.plsal_id = reqn_requisitions.rq_plant_4sale_code','left');
$this->db->join('tukai_pots',
'tukai_pots.pot_id = tukai_plants_4sale.plsal_pot_id','left');
$this->db->join('reqn_requisition_remarks',
'reqn_requisition_remarks.rqrem_reqn_id = reqn_requisitions.rq_id','left');
$this->db->order_by("rq_id","desc");
For complex where clause conditions you can use,
$this->db->where('<where condition here>', NULL, FALSE);
From docs:
$this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.
Try below code:
/* Replace table_name with appropriate table names */
$this->db->select("table_name.rq_id, table_name.rq_plant_4sale_code, table_name.rq_serial_number, table_name.rq_quantity_requested, table_name.rq_requester_farm_id,
table_name.rq_fulfiller_farm_id, table_name.rqpri_description, rqrem_remark,table_name.rqrem_remark_datetime, table_name.rq_created_datetime,
table_name.plsal_name_botanical, table_name.plsal_name_english, table_name.pot_code, table_name.rqpri_description ");
$this->db->from('reqn_requisitions');
$this->db->join('reqn_requisition_priorities','reqn_requisitions.rq_priority_rank = reqn_requisition_priorities.rqpri_rank','left');
$this->db->join('reqn_requisition_remarks','reqn_requisition_remarks.rqrem_reqn_id = reqn_requisitions.rq_id','left');
$this->db->join('tukai_plants_4sale','tukai_plants_4sale.plsal_id = reqn_requisitions.rq_plant_4sale_code','left');
$this->db->join('tukai_pots','tukai_pots.pot_id = tukai_plants_4sale.plsal_pot_id','left');
$this->db->where('reqn_requisition_remarks.rqrem_remark_datetime IN(SELECT MAX(rqrem_remark_datetime) AS dt FROM reqn_requisition_remarks GROUP BY rqrem_reqn_id', NULL, FALSE);
$this->db->where('table_name.rq_challan_id', 0);
$this->db->order_by("table_name.rq_id","desc");
$query = $this->db->get();
return $query->result();
An alternative:
If your query (anyhow) cannot be written using CI's Active Record, you can always use a simple method:
$this->db->query('<your SQL query here>');
For example:
$query = $this->db->query('SELECT rq_id, rq_plant_4sale_code, rq_serial_number,rq_quantity_requested, rq_requester_farm_id,rq_fulfiller_farm_id, rqpri_description,rqrem_remark,rqrem_remark_datetime, rq_created_datetime,
plsal_name_botanical, plsal_name_english, pot_code, rqpri_description
FROM (reqn_requisitions)
LEFT JOIN reqn_requisition_priorities ON(rq_priority_rank=rqpri_rank)
LEFT JOIN reqn_requisition_remarks ON(rq_id=rqrem_reqn_id)
LEFT JOIN tukai_plants_4sale ON(rq_plant_4sale_code=plsal_id)
LEFT JOIN tukai_pots ON(plsal_pot_id=pot_id)
WHERE rqrem_remark_datetime IN(SELECT MAX(rqrem_remark_datetime) AS dt FROM reqn_requisition_remarks GROUP BY rqrem_reqn_id ) AND rq_challan_id=0');
return $query->result();

Invalid parameter number error using DataTables with Laravel

When DataTables tries to get data, it always gets tripped up on this Eloquent query:
$items = Item::select([
DB::raw("images.url AS image"),
'items.id',
'items.sku',
'items.quantity',
DB::raw("IF(items.enabled, 'Yes', 'No') AS enabled")
])
->leftJoin('images', function ($j) {
$j->on('images.imageable_id', '=', 'items.id')
->where('images.imageable_type', '=', 'Item');
})
->leftJoin('order_items', 'items.id', '=', 'order_items.item_id')
->leftJoin('orders', 'orders.id', '=', 'order_items.order_id')
->where('items.store_id', 1)
->whereNull('items.deleted_at')
->whereIn('items.status', ['active', 'submitted'])
->groupBy('items.id');
The query works just fine as is and returns the desired results. However, DataTables tries to transform it into the following which produces the error:
select count(*) as aggregate from (select '1' as row from `items` left join `images` on `images`.`imageable_id` = `items`.`id` and `images`.`imageable_type` = 1 left join `order_items` on `items`.`id` = `order_items`.`item_id` left join `orders` on `orders`.`id` = `order_items`.`order_id` where `items`.`store_id` = 1 and `items`.`deleted_at` is null group by `items`.`id`) AS count_row_table
This produces this error specifically:
SQLSTATE[HY093]: Invalid parameter number
/home/vagrant/Projects/test.dev/vendor/laravel/framework/src/Illuminate/Database/Connection.php#301
When I execute that query directly on the MySQL database, it has no problem. This seems to be happening within Laravel only.
If I remove the ->leftJoin('images', function ($j) {...} part of the query then there is no error, but I need that join for the image.
How to get around this error?
Full error output returned to DataTables over AJAX:
{
"error":{
"type":"Illuminate\\Database\\QueryException",
"message":"SQLSTATE[HY093]: Invalid parameter number (SQL: select count(*) as aggregate from (select '1' as row from `items` left join `images` on `images`.`imageable_id` = `items`.`id` and `images`.`imageable_type` = 1 left join `order_items` on `items`.`id` = `order_items`.`item_id` left join `orders` on `orders`.`id` = `order_items`.`order_id` where `items`.`store_id` = active and `items`.`deleted_at` is null and `items`.`status` in (submitted, ?) group by `items`.`id`) AS count_row_table)",
"file":"\/home\/vagrant\/Projects\/test.dev\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Connection.php",
"line":625
}
}
I have had a similar issue today, not with DataTables but with a complex query being built using the standalone query builder. The issue was similar to yours with the left join, passing a closure to build a more complex join condition. I was using a where condition after the "on".
The solution was to chain "on" calls:
->leftJoin('images', function ($j) {
$j->on('images.imageable_id', '=', 'items.id')
// note the "on" rather than the "where" and the use of a raw statement
->on('images.imageable_type', '=', DB::raw('Item'));
})
I had this exact issue. The work around is not perfect since it will basically grab all the data twice, but it's the only way I could get it to work.
You have to do a ->get(); before sending it to ->make();. I honestly hope someone finds the right solution but for now:
Temp solution:
$data = DB::table('some_table');
$data->leftJoin('some_other_table', function($join)
{
$join->on('some_table.id', '=', 'some_other_table.id')
->where('some_table.something', '=', 'some_value');
});
$data->get();
return Datatables::of($data)->make();
This is with using the datatables package for Laravel: https://github.com/bllim/laravel4-datatables-package

mysql select from a view with where condition gives different result than executing the view definition with where condition

I have a view with the following definition:
select
`cb_trans_detail`.`numero_partida` AS `numero_partida`,
`cb_trans_head`.`fecha_partida` AS `fecha_partida`,
`cb_trans_detail`.`concepto_partida` AS `concepto_partida`,
`cb_cuenta`.`nombre_cuenta` AS `nombre_cuenta`,
`cb_cuenta`.`codigo_mayor` AS `codigo_mayor`,
`cb_mayor`.`nombre_mayor` AS `nombre_mayor`,
`cb_mayor`.`categoria` AS `categoria`,
`cb_categoria`.`nombre` AS `nombre`,
`cb_categoria`.`presentacion` AS `presentacion`,
`cb_trans_detail`.`codigo_cuenta` AS `codigo_cuenta`,
sum(`cb_trans_detail`.`debito_partida`) AS `Debitos`,
sum(`cb_trans_detail`.`credito_partida`) AS `Creditos`,
`cb_cuenta`.`saldo_inicial` AS `saldo_inicial`,
((`cb_cuenta`.`saldo_inicial` +
sum(`cb_trans_detail`.`debito_partida`)) -
sum(`cb_trans_detail`.`credito_partida`)) AS `Saldo`,
concat(`cb_mayor`.`categoria`,`cb_cuenta`.`codigo_mayor`,`cb_trans_detail`.`codigo_cuenta`)
AS `Codigo`
from
((((`cb_trans_detail` join `cb_cuenta`
on(((`cb_trans_detail`.`codigo_cuenta` = `cb_cuenta`.`codigo_cuenta`)
and (`cb_trans_detail`.`categoria` = `cb_cuenta`.`categoria`)
and (`cb_trans_detail`.`codigo_mayor` = `cb_cuenta`.`codigo_mayor`))))
join `cb_mayor` on(((`cb_cuenta`.`codigo_mayor` = `cb_mayor`.`codigo_mayor`)
and (`cb_cuenta`.`categoria` = `cb_mayor`.`categoria`))))
join `cb_categoria` on(((`cb_mayor`.`categoria` = `cb_categoria`.`categoria`)
and (`cb_trans_detail`.`categoria` = `cb_categoria`.`categoria`))))
left join `cb_trans_head` on((`cb_trans_detail`.`numero_partida` =
`cb_trans_head`.`numero_partida`)))
where
(`cb_categoria`.`presentacion` = '1')
group by concat(`cb_mayor`.`categoria`,`cb_cuenta`.`codigo_mayor`,
`cb_trans_detail`.`codigo_cuenta`)
If I select from this view as follows:
SELECT
`balance_general_view`.`numero_partida`,
`balance_general_view`.`fecha_partida`,
`balance_general_view`.`concepto_partida`,
`balance_general_view`.`nombre_cuenta`,
`balance_general_view`.`codigo_mayor`,
`balance_general_view`.`nombre_mayor`,
`balance_general_view`.`categoria`,
`balance_general_view`.`nombre`,
`balance_general_view`.`presentacion`,
`balance_general_view`.`codigo_cuenta`,
`balance_general_view`.`Debitos`,
`balance_general_view`.`Creditos`,
`balance_general_view`.`saldo_inicial`,
`balance_general_view`.`Saldo`,
`balance_general_view`.`Codigo`
FROM
`balance_general_view`
WHERE
`balance_general_view`.`fecha_partida` BETWEEN '2014-01-01' AND '2014-01-31'
this yields a different result than if I execute the query as follows:
select
`cb_trans_detail`.`numero_partida` AS `numero_partida`,
`cb_trans_head`.`fecha_partida` AS `fecha_partida`,
`cb_trans_detail`.`concepto_partida` AS `concepto_partida`,
`cb_cuenta`.`nombre_cuenta` AS `nombre_cuenta`,
`cb_cuenta`.`codigo_mayor` AS `codigo_mayor`,
`cb_mayor`.`nombre_mayor` AS `nombre_mayor`,
`cb_mayor`.`categoria` AS `categoria`,
`cb_categoria`.`nombre` AS `nombre`,
`cb_categoria`.`presentacion` AS `presentacion`,
`cb_trans_detail`.`codigo_cuenta` AS `codigo_cuenta`,
sum(`cb_trans_detail`.`debito_partida`) AS `Debitos`,
sum(`cb_trans_detail`.`credito_partida`) AS `Creditos`,
`cb_cuenta`.`saldo_inicial` AS `saldo_inicial`,
((`cb_cuenta`.`saldo_inicial` + sum(`cb_trans_detail`.`debito_partida`)) - sum(`cb_trans_detail`.`credito_partida`)) AS `Saldo`,
concat(`cb_mayor`.`categoria`,`cb_cuenta`.`codigo_mayor`,`cb_trans_detail`.`codigo_cuenta`) AS `Codigo`
from
((((`cb_trans_detail` join `cb_cuenta` on(((`cb_trans_detail`.`codigo_cuenta` = `cb_cuenta`.`codigo_cuenta`) and (`cb_trans_detail`.`categoria` = `cb_cuenta`.`categoria`) and (`cb_trans_detail`.`codigo_mayor` = `cb_cuenta`.`codigo_mayor`)))) join `cb_mayor` on(((`cb_cuenta`.`codigo_mayor` = `cb_mayor`.`codigo_mayor`) and (`cb_cuenta`.`categoria` = `cb_mayor`.`categoria`)))) join `cb_categoria` on(((`cb_mayor`.`categoria` = `cb_categoria`.`categoria`) and (`cb_trans_detail`.`categoria` = `cb_categoria`.`categoria`)))) left join `cb_trans_head` on((`cb_trans_detail`.`numero_partida` = `cb_trans_head`.`numero_partida`)))
where
(`cb_categoria`.`presentacion` = '1') and `cb_trans_head`.`fecha_partida` BETWEEN '2014-01-01' and '2014-01-31'
group by
concat(`cb_mayor`.`categoria`,`cb_cuenta`.`codigo_mayor`,`cb_trans_detail`.`codigo_cuenta`)
My question is: How to get the result I need using the view and filtering programatically instead of hard-coding the where condition? Thank you. If you need the individual table definitions let me know. Much appreciated.
If you use a left join to a table X and a condition in the WHERE-clause to this table X, you change your left join to an inner one. If you want to restrict the results by the values of this left joined table, you must use this condition in the ON clause of the left join instead:
...
LEFT JOIN
cb_trans_head
ON
cb_trans_detail.numero_partida = cb_trans_head.numero_partida
AND
cb_trans_head.fecha_partida BETWEEN '2014-01-01' and '2014-01-31'
...
If there's another one that I overlook, tread it the same way.

MYSQL IF Function

I am using two joins on the same table for two different select statements. I am wanting to implement an IF function, due to the fact that the table may contain a zero, I am wanting to substitue the zero for the word 'None'
Here is my SQL that works:
SELECT
CONCAT(`payments`.`AssignedTo`," - ",`people2`.`FName`," ",`people2`.`LName`) AS `AssignedTo`,
CONCAT(`payments`.`PersonID`," - ",`people`.`FName`," ",`people`.`LName`) AS `PersonName`
FROM `mb_payments` as `payments`
LEFT JOIN `mb_people` AS `people` ON `people`.`PersonID` = `payments`.`PersonID`
LEFT JOIN `mb_people` AS `people2` ON `people2`.`PersonID` = `payments`.`AssignedTo`
Here is my SQL with the IF function that does not work:
SELECT
IF(AssignedTo IS 0,'None', CONCAT(`payments`.`AssignedTo`," - ",`people2`.`FName`," ",`people2`.`LName`)),
CONCAT(`payments`.`PersonID`," - ",`people`.`FName`," ",`people`.`LName`) AS `PersonName`
FROM `mb_payments` as `payments`
LEFT JOIN `mb_people` AS `people` ON `people`.`PersonID` = `payments`.`PersonID`
LEFT JOIN `mb_people` AS `people2` ON `people2`.`PersonID` = `payments`.`AssignedTo`
You can use CASE statement in this case or if you want to use IF statement then your statement is wrong.
It should be:
SELECT
IF(AssignedTo = 0,'None', CONCAT(`payments`.`AssignedTo`," - ",`people2`.`FName`," ",`people2`.`LName`)) AS Result,
CONCAT(`payments`.`PersonID`," - ",`people`.`FName`," ",`people`.`LName`) AS `PersonName`
FROM `mb_payments` as `payments`
LEFT JOIN `mb_people` AS `people` ON `people`.`PersonID` = `payments`.`PersonID`
LEFT JOIN `mb_people` AS `people2` ON `people2`.`PersonID` = `payments`.`AssignedTo`
Check out this blog: http://timmurphy.org/2009/08/13/inline-if-and-case-statements-in-mysql/
I think you want ".. = 0", not "... IS 0". You use IS when comparing with NULL.

MySQL view returns more results with an AND?

When I do this:
select * from vw_active_employees where division IS NULL; --319 results
Makes sense. And, then I do this...
select * from vw_active_employees where division IS NULL AND udds IS NULL; -- over 1000 results
Whaaaaat?? MORE results??
So, I had to wrap the view as a subselect for it to return what I was expecting. Like this:
select vw_active_employees.* from (select * from vw_active_employees) tmp where division IS NULL AND udds IS NULL; --317 results
Can someone explain this? I've never had to do this in MS SQLSERVER - so this is foreign to me.
The SQL used to create this view actually joins a number of other views together. I'm not entirely sure it's helpful to see, but you asked for it :) It's basically
CREATE VIEW `vw_active_employees` AS
select
e.*,
`vw_employee_attributes_map`.`med_school_faculty`, `vw_employee_attributes_map`.`paid_clinic_faculty`, `vw_employee_attributes_map`.`volunteer_clinic_faculty`, `vw_employee_attributes_map`.`dept_vote_rights`, `vw_employee_attributes_map`.`emeritus`, `vw_employee_attributes_map`.`aoa_member`, `vw_employee_attributes_map`.`faculty_senate`, `vw_employee_attributes_map`.`faculty_senator_elect`, `vw_employee_attributes_map`.`faculty_senator_alt_elect`, `vw_employee_attributes_map`.`exec_comm_member`, `vw_employee_attributes_map`.`ucc`, `vw_employee_attributes_map`.`icc`, `vw_employee_attributes_map`.`va`, `vw_employee_attributes_map`.`uwmf`, `vw_employee_attributes_map`.`affiliate`, `vw_employee_attributes_map`.`aurora`, `vw_employee_attributes_map`.`website_searchable`,
`vw_employee_current_appointment_info`.`termination_date`, `vw_employee_current_appointment_info`.`last_promotion_date`, `vw_employee_current_appointment_info`.`promotion_due_date`, `vw_employee_current_appointment_info`.`last_reappointment_date`, `vw_employee_current_appointment_info`.`reappointment_duration`, `vw_employee_current_appointment_info`.`reappointment_due_date`, `vw_employee_current_appointment_info`.`non_renewal_date`, `vw_employee_current_appointment_info`.`roster`, `vw_employee_current_appointment_info`.`payroll`, `vw_employee_current_appointment_info`.`on_probation`, `vw_employee_current_appointment_info`.`probation_complete`, `vw_employee_current_appointment_info`.`probation_notify_sent_date`, `vw_employee_current_appointment_info`.`probation_end_date`, `vw_employee_current_appointment_info`.`uw_appointment_id`, `vw_employee_current_appointment_info`.`effective_date`, `vw_employee_current_appointment_info`.`percent`, `vw_employee_current_appointment_info`.`end_date`, `vw_employee_current_appointment_info`.`continuity_status`, `vw_employee_current_appointment_info`.`guaranteed_length`, `vw_employee_current_appointment_info`.`end_reason`, `vw_employee_current_appointment_info`.`midterm_eval_received`, `vw_employee_current_appointment_info`.`final_eval_received`, `vw_employee_current_appointment_info`.`annual_eval_letter_sent`, `vw_employee_current_appointment_info`.`annual_eval_sent_date`, `vw_employee_current_appointment_info`.`annual_eval_received`, `vw_employee_current_appointment_info`.`annual_eval_received_date`, `vw_employee_current_appointment_info`.`probation_month_done`, `vw_employee_current_appointment_info`.`seniority_date`, `vw_employee_current_appointment_info`.`represented`, `vw_employee_current_appointment_info`.`work_schedule`, `vw_employee_current_appointment_info`.`evaluation_end_date`, `vw_employee_current_appointment_info`.`evaluation_month_end`, `vw_employee_current_appointment_info`.`evaluation_sent_date`, `vw_employee_current_appointment_info`.`evaluation_completed`, `vw_employee_current_appointment_info`.`hiring_pi`, `vw_employee_current_appointment_info`.`appointment_type`, `vw_employee_current_appointment_info`.`appointment_type_code`, `vw_employee_current_appointment_info`.`appointment_classified`, `vw_employee_current_appointment_info`.`termination_type`, `vw_employee_current_appointment_info`.`head`, `vw_employee_current_appointment_info`.`secretary`, `vw_employee_current_appointment_info`.`division`, `vw_employee_current_appointment_info`.`supervisor_first_name`, `vw_employee_current_appointment_info`.`supervisor_last_name`, `vw_employee_current_appointment_info`.`title`, `vw_employee_current_appointment_info`.`title_code`, `vw_employee_current_appointment_info`.`udds`, `vw_employee_current_appointment_info`.`udds_code`,
`vw_employee_current_background_info`.`visa_holder`, `vw_employee_current_background_info`.`visa_type`, `vw_employee_current_background_info`.`visa_expiration_date`, `vw_employee_current_background_info`.`license`, `vw_employee_current_background_info`.`license_exp_date`, `vw_employee_current_background_info`.`dea`, `vw_employee_current_background_info`.`dea_expiration_date`, `vw_employee_current_background_info`.`national_provider_number`, `vw_employee_current_background_info`.`residency_location`, `vw_employee_current_background_info`.`residency_end_date`, `vw_employee_current_background_info`.`fellowship_location`, `vw_employee_current_background_info`.`fellowship_end_date`, `vw_employee_current_background_info`.`primary_board_cert`, `vw_employee_current_background_info`.`primary_cert_date`, `vw_employee_current_background_info`.`specialty_board_cert`, `vw_employee_current_background_info`.`specialty_cert_date`, `vw_employee_current_background_info`.`degree_info_reports`, `vw_employee_current_background_info`.`healthlink_id`, `vw_employee_current_background_info`.`uwmf_general_ledger_id`, `vw_employee_current_background_info`.`uwmf_employee_id`, `vw_employee_current_background_info`.`specialty`,
`vw_employee_current_compliance_info`.`hipaa_training_completed`, `vw_employee_current_compliance_info`.`sic_training_completed`, `vw_employee_current_compliance_info`.`background_check_completed`, `vw_employee_current_compliance_info`.`i9_completed`, `vw_employee_current_compliance_info`.`caregiver_applies`, `vw_employee_current_compliance_info`.`caregiver_check_completed`, `vw_employee_current_compliance_info`.`tb_completed`, `vw_employee_current_compliance_info`.`rubella_immunity_comfirmed`, `vw_employee_current_compliance_info`.`respiratory_test_completed`, `vw_employee_current_compliance_info`.`health_link`, `vw_employee_current_compliance_info`.`access_request_uwhc`, `vw_employee_current_compliance_info`.`rn_credentialing`, `vw_employee_current_compliance_info`.`bls_cert_expiration`, `vw_employee_current_compliance_info`.`uwhc_cred_submitted`,
`vw_employee_current_contact_info`.`employee_id`, `vw_employee_current_contact_info`.`ext_office`, `vw_employee_current_contact_info`.`area_code_office`, `vw_employee_current_contact_info`.`number_office`, `vw_employee_current_contact_info`.`country_code_office`, `vw_employee_current_contact_info`.`ext_home`, `vw_employee_current_contact_info`.`area_code_home`, `vw_employee_current_contact_info`.`number_home`, `vw_employee_current_contact_info`.`country_code_home`, `vw_employee_current_contact_info`.`address1_office`, `vw_employee_current_contact_info`.`address2_office`, `vw_employee_current_contact_info`.`city_office`, `vw_employee_current_contact_info`.`state_office`, `vw_employee_current_contact_info`.`zip_office`, `vw_employee_current_contact_info`.`mail_code_office`, `vw_employee_current_contact_info`.`address1_home`, `vw_employee_current_contact_info`.`address2_home`, `vw_employee_current_contact_info`.`city_home`, `vw_employee_current_contact_info`.`state_home`, `vw_employee_current_contact_info`.`zip_home`, `vw_employee_current_contact_info`.`email`
from employee e
left join vw_employee_attributes_map on e.id = vw_employee_attributes_map.employee_id
left join vw_employee_current_appointment_info on e.id = vw_employee_current_appointment_info.employee_id
left join vw_employee_current_background_info on e.id = vw_employee_current_background_info.employee_id
left join vw_employee_current_compliance_info on e.id = vw_employee_current_compliance_info.employee_id
left join vw_employee_current_contact_info on e.id = vw_employee_current_contact_info.employee_id
where e.active = 1
And the vw_employee_current_appointment_info which contains 'division' and 'udds' looks like:
CREATE VIEW `vw_employee_current_appointment_info` AS
select e.id as `employee_id`,
`appointment`.`termination_date`, `appointment`.`last_promotion_date`, `appointment`.`promotion_due_date`, `appointment`.`last_reappointment_date`, `appointment`.`reappointment_duration`, `appointment`.`reappointment_due_date`, `appointment`.`non_renewal_date`, `appointment`.`roster`, `appointment`.`payroll`, `appointment`.`on_probation`, `appointment`.`probation_complete`, `appointment`.`probation_notify_sent_date`, `appointment`.`probation_end_date`, `appointment`.`uw_appointment_id`, `appointment`.`effective_date`, `appointment`.`percent`, `appointment`.`end_date`, `appointment`.`continuity_status`, `appointment`.`guaranteed_length`, `appointment`.`end_reason`, `appointment`.`midterm_eval_received`, `appointment`.`final_eval_received`, `appointment`.`annual_eval_letter_sent`, `appointment`.`annual_eval_sent_date`, `appointment`.`annual_eval_received`, `appointment`.`annual_eval_received_date`, `appointment`.`probation_month_done`, `appointment`.`seniority_date`, `appointment`.`represented`, `appointment`.`work_schedule`, `appointment`.`evaluation_end_date`, `appointment`.`evaluation_month_end`, `appointment`.`evaluation_sent_date`, `appointment`.`evaluation_completed`, `appointment`.`hiring_pi`,
`appointment_type`.`name` as `appointment_type`, `appointment_type`.`code` as `appointment_type_code`, `appointment_type`.`classified` as `appointment_classified`,
`termination`.`name` as `termination_type`,
`appointment_division`.`head`, `appointment_division`.`secretary`,
`division`.`division_name` as `division`,
`supervisor`.`first_name` as `supervisor_first_name`, `supervisor`.`last_name` as `supervisor_last_name`,
`title`.`name` as `title`, `title`.`code` as `title_code`,
`udds`.`name` as `udds`, `udds`.`code` as `udds_code`
from employee e
left join appointment on appointment.employee_id = e.id and appointment.primary = 1
left join appointment_type on appointment.appointment_type_id = appointment_type.id
left join termination on appointment.termination_id = termination.id
left join appointment_division on appointment_division.appointment_id = appointment.id and appointment_division.primary = 1
left join division on appointment_division.division_id = division.id
left join appointment_supervisor on appointment_supervisor.appointment_id = appointment.id and appointment_supervisor.primary = 1
left join employee supervisor on appointment_supervisor.supervisor_id = supervisor.id
left join appointment_title on appointment_title.appointment_id = appointment.id and appointment_title.primary = 1
left join title on appointment_title.title_id = title.id
left join appointment_udds on appointment_udds.appointment_id = appointment.id and appointment_udds.primary = 1
left join udds on udds.id = appointment_udds.udds_id
you have used left join in your tables .when join condition is true than it has been select records those match in all tables than fetch records from left tables one by one and in this case your null condition is true and it is repeat the result set view
You are using left joins so your base table connects to the subsequent tables even if no value exists. However, when you begin to filter the subsequent tables you are specifying a that the subsequent table contain certain values. In this case there are probably only 319 values in the "vw_employee_current_appointment_info" with a null in the division field. When you add in the udds field there can be more fields that are null, because of the left join the division field is NULL by definition
So, the number of connections where "vw_employee_current_appointment_info" has udds as NULL is greater than the number of records where division is NULL, so it brings them all back. If you try this with equal joins then the number will be 319 max.