How can I avoid using the NOT IN and the SUBSELECT in the following query - sql

How can I avoid using the NOT IN subselect in this query and also avoid the subselect ?
select idTipoDocumento,idDocumentoTarea
from ArchivosTarea as a
inner join Tarea as b on a.idEstadoTarea=b.idTarea
where b.idTarea = 160
and idDocumentoTarea not in (select idDocumentoTarea
from ArchivosTarea as a
inner join tiposArchivos as b on a.idTipoDocumento = b.idTipoArchivo
inner join documentoSolicitud as c on b.idTipoArchivo = c.Id_tipo_archivo
inner join tarea as d on a.idEstadoTarea=d.idTarea
where d.idTarea = 160)
I know that probably a LEFT JOIN or something like that should do the trick but I have tried that and it does not provide me the same results as this query.
The actual idea is to avoid the SUBSELECT (of the WHERE) and also avoid the NOT IN.

Using left join:
Select A.idTipoDocumento,A.idDocumentoTarea from
(select idTipoDocumento,idDocumentoTarea
from ArchivosTarea as a
inner join Tarea as b on a.idEstadoTarea=b.idTarea
where b.idTarea = 160)A
left outer join
(select idDocumentoTarea from ArchivosTarea as a
inner join tiposArchivos as b on a.idTipoDocumento = b.idTipoArchivo
inner join documentoSolicitud as c on b.idTipoArchivo = c.Id_tipo_archivo
inner join tarea as d on a.idEstadoTarea=d.idTarea
where d.idTarea = 160)B
on A.idDocumentoTarea=B.idDocumentoTarea
where B.idDocumentoTarea is null

It happens that SQL Server has antijoin aka semiminus aka EXCEPTION JOIN. It return rows in the left argument that don't match when joined by the right.
select idTipoDocumento,idDocumentoTarea
from ArchivosTarea as a
inner join Tarea as b on a.idEstadoTarea=b.idTarea
and b.idTarea = 160
exception join (
select idDocumentoTarea
from ArchivosTarea as a
inner join tiposArchivos as b on a.idTipoDocumento = b.idTipoArchivo
inner join documentoSolicitud as c on b.idTipoArchivo = c.Id_tipo_archivo
inner join tarea as d on a.idEstadoTarea=d.idTarea
where d.idTarea = 160)
You can do this with LEFT JOIN. Also using NOT EXISTS.

Related

SQL inner join multi part identifier could not be bound

I have a stored procedure with a bunch of joins I can not figure out why this is not working - I get an error:
The multi-part identifier "[table.column]" could not be bound.
This is an altered bit of SQL the original is -
dbo.Release
INNER JOIN
dbo.Cartridge
INNER JOIN
dbo.PriceClass AS PriceClass ON dbo.Cartridge.PriceClassId = PriceClass.Id
INNER JOIN
dbo.CartridgeType ON dbo.Cartridge.CartridgeTypeId = dbo.CartridgeType.Id
ON dbo.Release.Id = dbo.Cartridge.ReleaseId
INNER JOIN
dbo.OemSegmentation
INNER JOIN
dbo.OemProduct ON dbo.OemSegmentation.OemProductId = dbo.OemProduct.Id
INNER JOIN
dbo.OemPlatform ON dbo.OemSegmentation.OemPlatformId = dbo.OemPlatform.Id
INNER JOIN
dbo.OemMediaType ON dbo.OemSegmentation.OemMediaTypeId = dbo.OemMediaType.Id
ON dbo.CartridgeType.Id = dbo.OemSegmentation.SupplCartTypeId
OR dbo.CartridgeType.Id = dbo.OemSegmentation.CartridgeTypeId
LEFT OUTER JOIN
dbo.CartridgeCoverage ON dbo.Cartridge.Id = dbo.CartridgeCoverage.CartridgeId
What I am trying to change it to -
dbo.Release
INNER JOIN
dbo.Cartridge
INNER JOIN
dbo.PriceClass AS PriceClass ON dbo.Cartridge.PriceClassId = PriceClass.Id
INNER JOIN
dbo.CartridgeType ON dbo.Cartridge.CartridgeTypeId = dbo.CartridgeType.Id
ON dbo.Release.Id = dbo.Cartridge.ReleaseId
INNER JOIN
dbo.OemProduct ON OemSegmentation.OemProductId = dbo.OemProduct.Id
INNER JOIN
dbo.OemPlatform ON dbo.OemSegmentation.OemPlatformId = dbo.OemPlatform.Id
INNER JOIN
dbo.OemMediaType ON dbo.OemSegmentation.OemMediaTypeId = dbo.OemMediaType.Id
LEFT OUTER JOIN
dbo.CartridgeCoverage ON dbo.Cartridge.Id = dbo.CartridgeCoverage.CartridgeId
The error happens on these lines
INNER JOIN
dbo.OemProduct ON OemSegmentation.OemProductId = dbo.OemProduct.Id
INNER JOIN
dbo.OemPlatform ON dbo.OemSegmentation.OemPlatformId = dbo.OemPlatform.Id
INNER JOIN
dbo.OemMediaType ON dbo.OemSegmentation.OemMediaTypeId = dbo.OemMediaType.Id
Once you have aliased your table, use the alias to use TWO PART names for columns. i.e [TableAlias].[ColumnName]
I belive you have use column namd Id in all your tables commonly, so whenever you are picking Id column just go for [TableName].Id.
It seems you missed join: "INNER JOIN dbo.OemSegmentation"

Best Join Strategy/Indexes for SQL Server

What is the best join strategy/indexes for this query:
SELECT
kwk.*, an.AuftragDatum, an.AbgabeDatum, an.BezahltDatum, an.AuftragStatus
FROM
KundenWerbenKunden kwk
INNER JOIN
Auftrag an ON an.AuftragNummer = kwk.AuftragNummer
WHERE
kwk.Deleted = 0
Table KundenWerbenKunden has 103950 rows with 103646 Deleted = 0 ones.
Table Auftrag has 3826552 rows.
In my real query I make some more joins:
INNER JOIN
Filiale fn WITH (NOLOCK) ON an.FilialeID = fn.FilialeID
INNER JOIN
Kunde kn ON an.KundeID = kn.KundeID
OUTER APPLY
(SELECT DISTINCT KSKNr
FROM KdZuordnung
WHERE KundeID = kn.KundeID) zn
LEFT JOIN
Anrede ann WITH (NOLOCK) ON kn.Anrede = ann.Anrede
INNER JOIN
AuftragArt aa WITH (NOLOCK) ON an.AuftragArtID = aa.AuftragArtID
INNER JOIN
AuftragGrund ag WITH (NOLOCK) ON an.AuftragGrundID = ag.AuftragGrundID
INNER JOIN
AuftragType at WITH (NOLOCK) ON an.AuftragTypeID = at.AuftragTypeID
For this query:
SELECT *
FROM KundenWerbenKunden kwk INNER JOIN
Auftrag an
ON an.AuftragNummer = kwk.AuftragNummer
WHERE kwk.Geloescht = 0;
And not knowing anything about the distribution of Geloescht, I would first try indexes on KundenWerbenKunden(Geloescht, AuftragNummer) and Auftrag(AuftragNummer).

Left Join not working

I am a SQL Server beginner and so I have been using MS Access to create queries and then have been amending them for SQL Server.
I have created a query which includes a left join, which works perfectly in Access but when I copy the SQL code across to SQL Server it does not show the null values and I cannot work out why.
I want to show all of the attribute values whether they include a value or not. Can anyone help? The code is as follows:
SELECT DISTINCT
tbLease.LeaseTitle
, tbAttributeValue.AttributeTemplateDefinitionLinkID
, tbAttributeValue.Value
FROM
((((tbBusinessUnit
LEFT JOIN
tbAttributeValue ON tbBusinessUnit.BusinessUnitID = tbAttributeValue.ParentID)
INNER JOIN
tbBuildingLinkBusinessUnit ON tbBusinessUnit.BusinessUnitID = tbBuildingLinkBusinessUnit.BusinessUnitID)
INNER JOIN
tbBuilding ON tbBuildingLinkBusinessUnit.BuildingID = tbBuilding.BuildingID)
INNER JOIN
(tbUnitLocation
INNER JOIN
tbUnit ON tbUnitLocation.UnitID = tbUnit.UnitID)
ON tbBuilding.BuildingID = tbUnitLocation.LocationID)
INNER JOIN
tbLease ON tbUnit.UnitID = tbLease.UnitID
WHERE
(((tbAttributeValue.AttributeTemplateDefinitionLinkID) = 30
Or (tbAttributeValue.AttributeTemplateDefinitionLinkID) = 31
Or (tbAttributeValue.AttributeTemplateDefinitionLinkID) = 32));
Hard to say what you want without some examples but you might want this:
WHERE coalesce(tbAttributeValue.AttributeTemplateDefinitionLinkID,30) in (30,31,32);
This will give you items where AttributeTemplateDefinitionLinkID is null
(that is it did not join on the left join) OR is one of those 3 values.
Right now if you don't join with the left join it will not display that row because of the where condition, so your left join is the same as an inner join.
The NULL values you would normally see with a left join are getting filtered out by your WHERE clause.
Any time you add filters to a WHERE clause that apply to an outer joined table, it will effectively make it the same as an inner join unless you include NULL values as an option in your where clause as well.
SELECT DISTINCT
tbLease.LeaseTitle,
tbAttributeValue.AttributeTemplateDefinitionLinkID,
tbAttributeValue.Value
FROM
tbBusinessUnit
LEFT JOIN tbAttributeValue ON tbBusinessUnit.BusinessUnitID = tbAttributeValue.ParentID
INNER JOIN tbBuildingLinkBusinessUnit ON tbBusinessUnit.BusinessUnitID = tbBuildingLinkBusinessUnit.BusinessUnitID
INNER JOIN tbBuilding ON tbBuildingLinkBusinessUnit.BuildingID = tbBuilding.BuildingID
INNER JOIN tbUnitLocation ON tbBuilding.BuildingID = tbUnitLocation.LocationID
INNER JOIN tbUnit ON tbUnitLocation.UnitID = tbUnit.UnitID
INNER JOIN tbLease ON tbUnit.UnitID = tbLease.UnitID
WHERE
tbAttributeValue.AttributeTemplateDefinitionLinkID in (30, 31, 32)
or tbAttributeValue.AttributeTemplateDefinitionLinkID is null
Move the right table filters from where clause to ON condition when you are using Left Outer Join else Left join will be implicitly converted to INNER JOIN. Try this
SELECT DISTINCT tblease.leasetitle,
tbattributevalue.attributetemplatedefinitionlinkid,
tbattributevalue.value
FROM tbbusinessunit
LEFT JOIN tbattributevalue
ON tbbusinessunit.businessunitid = tbattributevalue.parentid
AND ( tbattributevalue.attributetemplatedefinitionlinkid IN
( 30, 31, 32 )
OR tbattributevalue.attributetemplatedefinitionlinkid IS
NULL )
INNER JOIN tbbuildinglinkbusinessunit
ON tbbusinessunit.businessunitid =
tbbuildinglinkbusinessunit.businessunitid
INNER JOIN tbbuilding
ON tbbuildinglinkbusinessunit.buildingid = tbbuilding.buildingid
INNER JOIN tbunitlocation
ON tbbuilding.buildingid = tbunitlocation.locationid
INNER JOIN tbunit
ON tbunitlocation.unitid = tbunit.unitid
INNER JOIN tblease
ON tbunit.unitid = tblease.unitid

Inner join more than 2 tables in a single database

i want to innerjoin more than 3 tables in one select query in one database all of them are having rm_id as a common column but i want to display the rows of all tables in one sql query is it possible if it is then i would hearly request u to provide some code
select * from
bk_det inner join
bk_rep inner join
bk_sec inner join
mut_det inner join
rm_det inner join
soil_det
on
bk_det.rm_id = bk_rep.rm_id = bk_sec.rm_id = mut_det.rm_id = rm_det.rm_id = soil_det.rm_id
You need an on clause for each inner join. e.g.
select * from a
inner join b on a.id = b.id
inner join c on b.id = c.id
You are missing the ON clause for each join:
select *
from bk_det
inner join bk_rep
on bk_det.rm_id = bk_rep.rm_id
inner join bk_sec
on bk_rep.rm_id = bk_sec.rm_id
inner join mut_det
on bk_sec.rm_id = mut_det.rm_id
inner join rm_det
on mut_det.rm_id = rm_det.rm_id
inner join soil_det
on rm_det.rm_id = soil_det.rm_id
Note: you will have to check the join condition column names since I do not know your table structure
If you need help with learning join syntax, here is a great visual explanation of joins.
Since you are using an INNER JOIN this will return records if the rm_id exists in each table.
You might need to use a LEFT JOIN:
select *
from bk_det
left join bk_rep
on bk_det.rm_id = bk_rep.rm_id
left join bk_sec
on bk_rep.rm_id = bk_sec.rm_id
left join mut_det
on bk_sec.rm_id = mut_det.rm_id
left join rm_det
on mut_det.rm_id = rm_det.rm_id
left join soil_det
on rm_det.rm_id = soil_det.rm_id

Can you have an INNER JOIN without the ON keyword?

While debugging into some Oracle code, I came across this query:
SELECT TPM_TASK.TASKID FROM TPM_GROUP
INNER JOIN TPM_USERGROUPS ON TPM_GROUP.GROUPID = TPM_USERGROUPS.GROUPID
INNER JOIN TPM_TASK
INNER JOIN TPM_GROUPTASKS ON TPM_TASK.TASKID = TPM_GROUPTASKS.TASKID
INNER JOIN TPM_PROJECTVERSION ON TPM_TASK.PROJECTID = TPM_PROJECTVERSION.PROJECTID AND TPM_TASK.VERSIONID = TPM_PROJECTVERSION.VERSIONID
INNER JOIN TPM_TASKSTAGE ON TPM_TASK.STAGEID = TPM_TASKSTAGE.STAGEID
INNER JOIN TPM_PROJECTSTAGE ON TPM_PROJECTVERSION.STAGEID = TPM_PROJECTSTAGE.STAGEID
ON TPM_GROUP.GROUPID = TPM_GROUPTASKS.GROUPID
I'm confused by the line:
INNER JOIN TPM_TASK
I haven't seen a JOIN without an ON clause before. Also confusing is the line:
ON TPM_GROUP.GROUPID = TPM_GROUPTASKS.GROUPID
This seems like a random ON clause without any matching JOIN. The query runs without any errors, and returns a bunch of data, so obvious the syntax is perfectly valid. Can someone shed some light on exactly what's going on here?
Small universe... I ran across a tool generating this syntax yesterday and was rather flummoxed.
Apparently,
FROM a
INNER JOIN b
INNER JOIN c ON (b.id = c.id)
ON (a.id = c.id)
is equivalent to a nested subquery
FROM a
INNER JOIN (SELECT <<list of columns>>
FROM b
INNER JOIN c ON (b.id=c.id)) c
ON (a.id = c.id)
I think that this is only a problem of ordering your query (since there are only INNER JOINs, the order of them is not really that important). I rearrenged your query and now it looks like this:
SELECT TPM_TASK.TASKID
FROM TPM_GROUP
INNER JOIN TPM_USERGROUPS
ON TPM_GROUP.GROUPID = TPM_USERGROUPS.GROUPID
INNER JOIN TPM_GROUPTASKS
ON TPM_GROUP.GROUPID = TPM_GROUPTASKS.GROUPID
INNER JOIN TPM_TASK
ON TPM_TASK.TASKID = TPM_GROUPTASKS.TASKID
INNER JOIN TPM_PROJECTVERSION
ON TPM_TASK.PROJECTID = TPM_PROJECTVERSION.PROJECTID
AND TPM_TASK.VERSIONID = TPM_PROJECTVERSION.VERSIONID
INNER JOIN TPM_TASKSTAGE
ON TPM_TASK.STAGEID = TPM_TASKSTAGE.STAGEID
INNER JOIN TPM_PROJECTSTAGE
ON TPM_PROJECTVERSION.STAGEID = TPM_PROJECTSTAGE.STAGEID
Does it make more sense to you now?, it does to me.
It'd look fine if it had parenthesis in there...
SELECT TPM_TASK.TASKID
FROM
TPM_GROUP
INNER JOIN TPM_USERGROUPS ON TPM_GROUP.GROUPID = TPM_USERGROUPS.GROUPID
INNER JOIN (
TPM_TASK
INNER JOIN TPM_GROUPTASKS ON TPM_TASK.TASKID = TPM_GROUPTASKS.TASKID
INNER JOIN TPM_PROJECTVERSION ON TPM_TASK.PROJECTID = TPM_PROJECTVERSION.PROJECTID
AND TPM_TASK.VERSIONID = TPM_PROJECTVERSION.VERSIONID
INNER JOIN TPM_TASKSTAGE ON TPM_TASK.STAGEID = TPM_TASKSTAGE.STAGEID
INNER JOIN TPM_PROJECTSTAGE ON TPM_PROJECTVERSION.STAGEID = TPM_PROJECTSTAGE.STAGEID
) ON TPM_GROUP.GROUPID = TPM_GROUPTASKS.GROUPID
but since they are all inner joins I agree with Lamak's answer.