It is not clear to me what is the behaviour of a LEFT JOIN if you try to JOIN on a column that may be NULL.
E.g.
SELECT columns
FROM
EmployeePayment ep JOIN EmployeePaymentGroup g ON g.group_id = ep.group_id AND g.subsidiary_id = ep.subsidiary_id
LEFT JOIN EmployeeSalaryDetails esd USING (department_id)
LEFT JOIN Employee e ON e.id = esd.emp_id
What happens if the INNER JOIN of EmployeePayment and EmployeePaymentGroup return 1 record and then the second LEFT JOIN on EmployeeSalaryDetails retains this record but this record has as esd.emp_id a NULL value and try to LEFT JOIN on Employee on that NULL value.
I know that NULLs are tricky so I was wondering how does the LEFT JOIN cope with NULLs
Note:
I opened a question earlier about JOINs but the comment of Abhik Chakraborty make me realise that there was a problem with a NULL value in a condition
If you have a LEFT JOIN and the right table returns nothing (NULL) all the fields belonging to the right table in the projection are simply NULL, but you still get your result from the left table. RIGHT JOIN has the opposite behavior and INNER JOIN will not return anything.
SELECT * FROM `left_table` LEFT JOIN `right_table`
NULL = NULL evaluates to UNKNOWN (which means “no, don’t join because I have no clue if we are allowed to.”) and the projection will only contain the results from the left table.
Of course there are ways to go around this problem:
SELECT *
FROM `left_table` AS `l`
LEFT JOIN `right_table` AS `r`
ON `r`.`id` <=> `l`.`id`
Now checks against NULL will work normally as you are used to (NULL <=> NULL is 1 and 'value' <=> NULL is 0). Also see the documentation for the equal to operator.
You can use isnull(cast()) function to convert the null record in a type and give it a value that is also in the employee column in order to join them based on that value.
LEFT JOIN EmployeeSalaryDetails esd on isnull((esd.department_id, "input here value of id") = "input here the value of the column"
Here is a example:
Inner join FORECAST_Claims b on (isnull(cast(a.Durg_Key as varchar(20)),'UNKNOWN') = isnull(cast(b.Durg_Key as varchar(20)),'UNKNOWN')
Related
I need to retrieve all default settings from the settings table but also grab the character setting if exists for x character.
But this query is only retrieving those settings where character is = 1, not the default settings if the user havent setted anyone.
SELECT `settings`.*, `character_settings`.`value`
FROM (`settings`)
LEFT JOIN `character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
WHERE `character_settings`.`character_id` = '1'
So i should need something like this:
array(
'0' => array('somekey' => 'keyname', 'value' => 'thevalue'),
'1' => array('somekey2' => 'keyname2'),
'2' => array('somekey3' => 'keyname3')
)
Where key 1 and 2 are the default values when key 0 contains the default value with the character value.
The where clause is filtering away rows where the left join doesn't succeed. Move it to the join:
SELECT `settings`.*, `character_settings`.`value`
FROM `settings`
LEFT JOIN
`character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
AND `character_settings`.`character_id` = '1'
When making OUTER JOINs (ANSI-89 or ANSI-92), filtration location matters because criteria specified in the ON clause is applied before the JOIN is made. Criteria against an OUTER JOINed table provided in the WHERE clause is applied after the JOIN is made. This can produce very different result sets. In comparison, it doesn't matter for INNER JOINs if the criteria is provided in the ON or WHERE clauses -- the result will be the same.
SELECT s.*,
cs.`value`
FROM SETTINGS s
LEFT JOIN CHARACTER_SETTINGS cs ON cs.setting_id = s.id
AND cs.character_id = 1
If I understand your question correctly you want records from the settings database if they don't have a join accross to the character_settings table or if that joined record has character_id = 1.
You should therefore do
SELECT `settings`.*, `character_settings`.`value`
FROM (`settings`)
LEFT OUTER JOIN `character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
WHERE `character_settings`.`character_id` = '1' OR
`character_settings`.character_id is NULL
You might find it easier to understand by using a simple subquery
SELECT `settings`.*, (
SELECT `value` FROM `character_settings`
WHERE `character_settings`.`setting_id` = `settings`.`id`
AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`
The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.
Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.
SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'
For this problem, as for many others involving non-trivial left joins such as left-joining on inner-joined tables, I find it convenient and somewhat more readable to split the query with a with clause. In your example,
with settings_for_char as (
select setting_id, value from character_settings where character_id = 1
)
select
settings.*,
settings_for_char.value
from
settings
left join settings_for_char on settings_for_char.setting_id = settings.id;
The way I finally understand the top answer is realising (following the Order Of Execution of the SQL query ) that the WHERE clause is applied to the joined table thereby filtering out rows that do not satisfy the WHERE condition from the joined (or output) table. However, moving the WHERE condition to the ON clause applies it to the individual tables prior to joining. This enables the left join to retain rows from the left table even though some column entries of those rows (entries from the right tables) do not satisfy the WHERE condition.
The result is correct based on the SQL statement. Left join returns all values from the right table, and only matching values from the left table.
ID and NAME columns are from the right side table, so are returned.
Score is from the left table, and 30 is returned, as this value relates to Name "Flow". The other Names are NULL as they do not relate to Name "Flow".
The below would return the result you were expecting:
SELECT a.*, b.Score
FROM #Table1 a
LEFT JOIN #Table2 b
ON a.ID = b.T1_ID
WHERE 1=1
AND a.Name = 'Flow'
The SQL applies a filter on the right hand table.
I need to retrieve all default settings from the settings table but also grab the character setting if exists for x character.
But this query is only retrieving those settings where character is = 1, not the default settings if the user havent setted anyone.
SELECT `settings`.*, `character_settings`.`value`
FROM (`settings`)
LEFT JOIN `character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
WHERE `character_settings`.`character_id` = '1'
So i should need something like this:
array(
'0' => array('somekey' => 'keyname', 'value' => 'thevalue'),
'1' => array('somekey2' => 'keyname2'),
'2' => array('somekey3' => 'keyname3')
)
Where key 1 and 2 are the default values when key 0 contains the default value with the character value.
The where clause is filtering away rows where the left join doesn't succeed. Move it to the join:
SELECT `settings`.*, `character_settings`.`value`
FROM `settings`
LEFT JOIN
`character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
AND `character_settings`.`character_id` = '1'
When making OUTER JOINs (ANSI-89 or ANSI-92), filtration location matters because criteria specified in the ON clause is applied before the JOIN is made. Criteria against an OUTER JOINed table provided in the WHERE clause is applied after the JOIN is made. This can produce very different result sets. In comparison, it doesn't matter for INNER JOINs if the criteria is provided in the ON or WHERE clauses -- the result will be the same.
SELECT s.*,
cs.`value`
FROM SETTINGS s
LEFT JOIN CHARACTER_SETTINGS cs ON cs.setting_id = s.id
AND cs.character_id = 1
If I understand your question correctly you want records from the settings database if they don't have a join accross to the character_settings table or if that joined record has character_id = 1.
You should therefore do
SELECT `settings`.*, `character_settings`.`value`
FROM (`settings`)
LEFT OUTER JOIN `character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
WHERE `character_settings`.`character_id` = '1' OR
`character_settings`.character_id is NULL
You might find it easier to understand by using a simple subquery
SELECT `settings`.*, (
SELECT `value` FROM `character_settings`
WHERE `character_settings`.`setting_id` = `settings`.`id`
AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`
The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.
Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.
SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'
For this problem, as for many others involving non-trivial left joins such as left-joining on inner-joined tables, I find it convenient and somewhat more readable to split the query with a with clause. In your example,
with settings_for_char as (
select setting_id, value from character_settings where character_id = 1
)
select
settings.*,
settings_for_char.value
from
settings
left join settings_for_char on settings_for_char.setting_id = settings.id;
The way I finally understand the top answer is realising (following the Order Of Execution of the SQL query ) that the WHERE clause is applied to the joined table thereby filtering out rows that do not satisfy the WHERE condition from the joined (or output) table. However, moving the WHERE condition to the ON clause applies it to the individual tables prior to joining. This enables the left join to retain rows from the left table even though some column entries of those rows (entries from the right tables) do not satisfy the WHERE condition.
The result is correct based on the SQL statement. Left join returns all values from the right table, and only matching values from the left table.
ID and NAME columns are from the right side table, so are returned.
Score is from the left table, and 30 is returned, as this value relates to Name "Flow". The other Names are NULL as they do not relate to Name "Flow".
The below would return the result you were expecting:
SELECT a.*, b.Score
FROM #Table1 a
LEFT JOIN #Table2 b
ON a.ID = b.T1_ID
WHERE 1=1
AND a.Name = 'Flow'
The SQL applies a filter on the right hand table.
I need a help in the mysql query.
SELECT `main_table`.*, `lea`.`account_id`
FROM `lists_list` AS `main_table`
INNER JOIN `list_account` AS `lea` ON lea.list_id=main_table.id
INNER JOIN `list_customer` AS `customer` ON main_table.id = customer.list_id
WHERE ((`customer.customer_id` = '1') OR (`lea.account_id` = '1'))
Now my problem is, I need to show lists that have a link type of "B" / "C" that have no list accounts in list_account and list_customer table , if the customer's Account matches that type in lists_list table
Could you please help in this.
That is actually pretty easy, just use LEFT JOIN instead of INNER JOIN:
SELECT `main_table`.*, `lea`.`account_id`
FROM `lists_list` AS `main_table`
LEFT JOIN `list_account` AS `lea` ON lea.list_id=main_table.id
LEFT JOIN `list_customer` AS `customer` ON main_table.id = customer.list_id
WHERE ((`customer.customer_id` = '1') OR (`lea.account_id` = '1'))
An INNER JOIN requires a record on the left and right side to exist, while LEFT JOIN will also return records where the right side does not exist (leaving the fields from that table with NULL as their value).
I have following 3 tables(Organization, OrganizationAddress, Address).Each organizations has more than one address and one of them is primary.if an organization has primary address,I need to select the primary address else that column can be null or blank.
How can i write a sql sub query in mysql?.
Please help me,
Thank you,
You just need a LEFT JOIN
select a.orgid, b.orgaddressid, c.address
from organization a
left join organization_address b on a.orgid = b.orgid and b.isprimaryaddress = 'YES'
left join address c on b.orgaddressid = c.addressid
where a.orgid = 1;
Maybe something like this. I think you need to use LEFT JOIN for both tables:
select
organization.orgid,
organization_address.orgaddressid,
address.address
from
organization
LEFT JOIN organization_address
ON organization_address.orgid = organization.orgid
AND organization_address.isprimaryaddress = 'YES'
LEFT JOIN address
ON organization_address.orgaddressid = address.addressid;
A LEFT JOIN selects rows in the left table and matching rows in the right table if there are matching rows in the right table. If there aren't any matching rows in the right table the query will return NULL for the columns from the right table.
SELECT o.OrgId, oa.OrgaddressId, a.Address FROM Organization AS o
LEFT JOIN 'Organization Address' AS oa ON oa.OrgId=o.OrgId
LEFT JOIN Address AS a ON a.AddressId=oa.OrgAddressId
WHERE oa.IsPrimaryId='YES';
Sub Query is slower then join query, so i just inform to you please ignore sub query
if you want to get this type of result you can use Left join
select a.orgid, b.orgaddressid, c.address
from organization a
left join organization_address b on a.orgid = b.orgid and b.isprimaryaddress = 'YES'
left join address c on b.orgaddressid = c.addressid
where a.orgid = 1;
Left join means
returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match.
visit the Types of join in google you can get more idea
I have 4 tables as follows; SCHEDULES, SCHEDULE_OVERRIDE, SCHEDULE_LOCATION_OVERRIDES and LOCATION
I need to return ALL rows from all tables so running this query works fine, adding NULL values for any values that are not present:
SELECT.....
FROM (schedule s LEFT JOIN schedule_override so ON so.schedule_id = s.id)
LEFT JOIN schedule_location_override slo ON slo.schedule_override_id = so.id
LEFT JOIN location l ON slo.location_id = l.id
ORDER BY s.id, so.id, slo.id, l.id
I then need to restict results on the schedule_override end_date field. My problem is, as soon as I do this, no results for the SCHEDULE table are returned at all. I need all schedules to be returned, even if the overrides end_date criteria is not met.
Heres what I am using:
SELECT.....
FROM (schedule s LEFT JOIN schedule_override so ON so.schedule_id = s.id)
LEFT JOIN schedule_location_override slo ON slo.schedule_override_id = so.id
LEFT JOIN location l ON slo.location_id = l.id
WHERE so.end_date > '2011-01-30' OR so.end_date IS NULL
ORDER BY s.id, so.id, slo.id, l.id
Appreciate any thoughts/comments.
Best regards, Ben.
Have you tried putting it in the ON clause?
SELECT.....
FROM (schedule s LEFT JOIN schedule_override so ON so.schedule_id = s.id AND (so.end_date > '2011-01-30' OR so.end_date IS NULL))
LEFT JOIN schedule_location_override slo ON slo.schedule_override_id = so.id
LEFT JOIN location l ON slo.location_id = l.id
ORDER BY s.id, so.id, slo.id, l.id
That's a quite common mistake with outer Joins.
You need to put everything that limits the Join into the "ON" part for that table, otherwise you are effectively transforming the join to an inner one.
So move the WHERE clause in this case into the ON-part of the schedule_override and you should be fine.
Yes, when you left join, it could be that a row is not found, and the field is NULL in the result. When you add a condition in the WHERE clause, the value must match that condition, which it won't if it's NULL.
That shouldn't be a problem, because you explicitly check for NULL, so I don't really know why this condition fails, unless it does return a date, but that date is befor 2011-01-30.
Anyway, you could try to move the condition to the join. It will eliminate the need to check for NULL, although it shouldn't make a difference really.
SELECT.....
FROM
schedule s
LEFT JOIN schedule_override so
ON so.schedule_id = s.id
AND so.end_date > '2011-01-30'
...