I'm writing a stored procedure that looks something like this:
SELECT
Positions.PositionId
,Positions.Title
,Positions.Location
,Positions.Description
,Positions.MaximumSalary
,PositionsDepartments.Description Department
,PositionsSubDepartments.Description Subdepartment
,PositionsDepartments.DepartmentId DepartmentId
,PositionsSubDepartments.SubDepartmentId SubdepartmentId
,#TheRole TheRole
,#Essentials Essentials
,#Desirable Desirable
,Positions.Published
,Positions.LastUpdatedDate
,PositionsStatus.Description Status
FROM
Positions
WITH (NOLOCK)
INNER JOIN PositionsStatus ON Positions.StatusId = PositionsStatus.StatusId
INNER JOIN PositionsSubDepartments ON Positions.SubDepartmentId = PositionsSubDepartments.SubDepartmentId
INNER JOIN PositionsDepartments ON PositionsSubDepartments.DepartmentId = PositionsDepartments.DepartmentId
WHERE
Positions.PositionId = #PositionId
BUT the Positions.SubDepartmentId could now be null - which means I don't get all the data back that I'm expecting. I've tried this but get a load of duplicate data back:
SELECT
Positions.PositionId
,Positions.Title
,Positions.Location
,Positions.Description
,Positions.MaximumSalary
,PositionsDepartments.Description Department
,PositionsSubDepartments.Description Subdepartment
,PositionsDepartments.DepartmentId DepartmentId
,PositionsSubDepartments.SubDepartmentId SubdepartmentId
,#TheRole TheRole
,#Essentials Essentials
,#Desirable Desirable
,Positions.Published, Positions.LastUpdatedDate
,PositionsStatus.Description Status
FROM
Positions
WITH (NOLOCK)
INNER JOIN PositionsStatus ON Positions.StatusId = PositionsStatus.StatusId
INNER JOIN PositionsSubDepartments ON Positions.SubDepartmentId = PositionsSubDepartments.SubDepartmentId OR ( Positions.SubDepartmentId IS NULL)
INNER JOIN PositionsDepartments ON PositionsSubDepartments.DepartmentId = PositionsDepartments.DepartmentId
WHERE
Positions.PositionId = #PositionId
What am I doing wrong?
You need to use a left join when an entry could be null
SELECT
Positions.[PositionId]
,Positions.[Title]
,Positions.[Location]
,Positions.[Description]
,Positions.[MaximumSalary]
,PositionsDepartments.[Description] Department
,PositionsSubDepartments.[Description] Subdepartment
,PositionsDepartments.[DepartmentId] DepartmentId
,PositionsSubDepartments.[SubDepartmentId] SubdepartmentId
,#TheRole TheRole
,#Essentials Essentials
,#Desirable Desirable
,Positions.[Published]
,Positions.[LastUpdatedDate]
,PositionsStatus.[Description] Status
FROM
Positions WITH (NOLOCK)
INNER JOIN PositionsStatus ON Positions.StatusId = PositionsStatus.StatusId
LEFT JOIN PositionsSubDepartments ON Positions.SubDepartmentId = PositionsSubDepartments.SubDepartmentId
LEFT JOIN PositionsDepartments ON PositionsSubDepartments.DepartmentId = PositionsDepartments.DepartmentId
WHERE
Positions.PositionId = #PositionId
You might also find the following useful: http://www.tutorialspoint.com/sql/sql-left-joins.htm
select Positions.PositionId, Positions.Title, Positions.Location,Positions.Description,Positions.MaximumSalary,
PositionsDepartments.Description Department, PositionsSubDepartments.Description Subdepartment, PositionsDepartments.DepartmentId DepartmentId, PositionsSubDepartments.SubDepartmentId SubdepartmentId,
#TheRole TheRole, #Essentials Essentials, #Desirable Desirable,
Positions.Published, Positions.LastUpdatedDate, PositionsStatus.Description Status
FROM Positions
WITH (NOLOCK)
INNER JOIN PositionsStatus ON Positions.StatusId = PositionsStatus.StatusId
LEFT JOIN PositionsSubDepartments ON Positions.SubDepartmentId = PositionsSubDepartments.SubDepartmentId
LEFT JOIN PositionsDepartments ON PositionsSubDepartments.DepartmentId = PositionsDepartments.DepartmentId
WHERE Positions.PositionId = #PositionId
Fixed it - thanks for your help:
select Positions.PositionId, Positions.Title, Positions.Location, Positions.Description, Positions.MaximumSalary, Positions.DepartmentId, Positions.SubDepartmentId,
PositionsDepartments.Description Department, PositionsSubDepartments.Description Subdepartment, PositionsSubDepartments.SubDepartmentId SubdepartmentId,
#TheRole TheRole, #Essentials Essentials, #Desirable Desirable,
Positions.Published, Positions.LastUpdatedDate, PositionsStatus.Description Status
FROM Positions
WITH (NOLOCK)
INNER JOIN PositionsStatus ON Positions.StatusId = PositionsStatus.StatusId
LEFT JOIN PositionsSubDepartments
ON PositionsSubDepartments.SubDepartmentId = Positions.SubDepartmentId OR (Positions.SubDepartmentId IS NULL AND PositionsSubDepartments.SubDepartmentId IS NULL)
LEFT JOIN PositionsDepartments
ON Positions.DepartmentId = PositionsDepartments.DepartmentId
WHERE Positions.PositionId = #PositionId
Related
First, I searched about the same problem but I didn't find an appropriate solution.
My problem is with the following code, it's returning wrong results:
SELECT FbID,FhID,
FbRef,
FbDate,
(D.AccName) AS DName,
FbQuan,
CONCAT(CategoryName,'-',ProductName) AS ProdName,
(C.AccName) AS CusName,
FhPurPrice,FbSalePrice,
(R.AccName) AS ResoName,
Curr1.CurrencyName,
Curr2.CurrencyName,
Plc1.PlaceName AS FhResoPlaceName,
Plc2.PlaceName AS FbCusPlaceName,
'linked' AS xLinkStatus,
1 AS xStatus
FROM tblfatora2 F2
INNER JOIN tblfatora1 F1 ON F1.FhRef = F2.FhRef
INNER JOIN tblproducts P ON P.ProductID = F1.FhProduct
INNER JOIN tblcategories CT ON CT.CategoryID = P.ProductCategory
INNER JOIN tblaccounts R ON R.AccID = F1.FhReso
INNER JOIN tblaccounts C ON C.AccID = F2.FbCus
INNER JOIN tblaccounts D ON D.AccID = F1.FhDriver
INNER JOIN tblcurrencies Curr1 ON C.AccCurrID = Curr1.CurrencyID
INNER JOIN tblcurrencies Curr2 ON R.AccCurrID = Curr2.CurrencyID
LEFT JOIN tblplaces Plc1 ON F1.FhResoPlace = Plc1.PlaceID
LEFT JOIN tblplaces Plc2 ON F2.FbCusPlace = Plc2.PlaceID
WHERE FIND_IN_SET(`FhID`, '18313,18314')
ORDER BY FbDate, FbID
the results that it gives me are: enter image description here
note: I use FIND_IN_SET here because I can't use (IN) where I use that SQL statement in a procedure inside vb.net code:
Public Sub MySql_GetLinked()
xDtAll = New DataTable()
Dim xPar(0) As MySqlParameter
xPar(0) = New MySqlParameter("#FhID", MySqlDbType.String) With {
.Value = LinkedFatora}
xClsMySql.GetData(xSqlLinked, xDtAll, xPar)
End Sub
So I fill the variable (LinkedFatora) by loop and I use the same SQL statement but I replace (WHERE FIND_IN_SET('FhID', '18313,18314')) with (WHERE FIND_IN_SET('FhID', #FhID)).
I looked for the error's reason but couldn't catch it.
I found the problem, it's changing (WHERE FIND_IN_SET(FhID, '18313,18314')) to (WHERE FIND_IN_SET(FbID, '18313,18314')):
SELECT FbID,FhID,
FbRef,
FbDate,
(D.AccName) AS DName,
FbQuan,
CONCAT(CategoryName,'-',ProductName) AS ProdName,
(C.AccName) AS CusName,
FhPurPrice,FbSalePrice,
(R.AccName) AS ResoName,
Curr1.CurrencyName,
Curr2.CurrencyName,
Plc1.PlaceName AS FhResoPlaceName,
Plc2.PlaceName AS FbCusPlaceName,
'linked' AS xLinkStatus,
1 AS xStatus
FROM tblfatora2 F2
INNER JOIN tblfatora1 F1 ON F1.FhRef = F2.FhRef
INNER JOIN tblproducts P ON P.ProductID = F1.FhProduct
INNER JOIN tblcategories CT ON CT.CategoryID = P.ProductCategory
INNER JOIN tblaccounts R ON R.AccID = F1.FhReso
INNER JOIN tblaccounts C ON C.AccID = F2.FbCus
INNER JOIN tblaccounts D ON D.AccID = F1.FhDriver
INNER JOIN tblcurrencies Curr1 ON C.AccCurrID = Curr1.CurrencyID
INNER JOIN tblcurrencies Curr2 ON R.AccCurrID = Curr2.CurrencyID
LEFT JOIN tblplaces Plc1 ON F1.FhResoPlace = Plc1.PlaceID
LEFT JOIN tblplaces Plc2 ON F2.FbCusPlace = Plc2.PlaceID
WHERE FIND_IN_SET(`FbID`, '18313,18314')
ORDER BY FbDate, FbID
I have an SQL query like below which has a where clause as WHERE pg.active=1 AND tcg.active=1 AND tpg.active=1,issue right now is that one or all of pg.active tcg.active ,tpg.active is set to 1 at any time,in the case where one of these is not set to 1 query doesn't return anything.
How do I change the where clause to return if any of pg.active tcg.active ,tpg.active is set to 1?
SELECT
..........
FROM software_products_software_images spsi
INNER JOIN software_images si ON si.software_image_id = spsi.software_image_id
INNER JOIN software_products sp ON sp.id = spsi.software_product_id
LEFT JOIN software_products_software_images_testplan_gate tpg ON tpg.software_products_software_images_id = spsi.Id
LEFT JOIN test_suites tp ON tp.id = tpg.testplan_id
LEFT JOIN software_products_software_images_testcase_gate tcg ON tcg.software_products_software_images_id = spsi.Id
LEFT JOIN test_cases tc ON tc.id = tcg.testcase_id
LEFT JOIN test_suites ts ON ts.id = tc.test_suite_id
LEFT JOIN software_products_software_images_percentage_gate pg ON pg.software_products_software_images_id = spsi.Id
...........................
WHERE pg.active=1 AND tcg.active=1 AND tpg.active=1
AND si.software_image='NHSS.QSDK.7.0.1' ORDER BY si.software_image, ts.suite_name
I believe you need to encapsulate the OR part of the WHERE statement in round brackets so that it returns a TRUE on any OR match along with your other conditions.
SELECT
..........
FROM software_products_software_images spsi
INNER JOIN software_images si ON si.software_image_id = spsi.software_image_id
INNER JOIN software_products sp ON sp.id = spsi.software_product_id
LEFT JOIN software_products_software_images_testplan_gate tpg ON tpg.software_products_software_images_id = spsi.Id
LEFT JOIN test_suites tp ON tp.id = tpg.testplan_id
LEFT JOIN software_products_software_images_testcase_gate tcg ON tcg.software_products_software_images_id = spsi.Id
LEFT JOIN test_cases tc ON tc.id = tcg.testcase_id
LEFT JOIN test_suites ts ON ts.id = tc.test_suite_id
LEFT JOIN software_products_software_images_percentage_gate pg ON pg.software_products_software_images_id = spsi.Id
...........................
WHERE (pg.active=1 OR tcg.active=1 OR tpg.active=1)
AND si.software_image='NHSS.QSDK.7.0.1' ORDER BY si.software_image, ts.suite_name
I have the following query and would like to convert it to using a left outer join instead of a not in to see if it would run faster that way. It's currently taking this query about 40 seconds to run on our database. I'm not familiar enough with using outer joins for this type of thing to convert it myself.
select
c.contact_id as contact_id,
c.orgid as organization_id,
c.first_name as first_name,
c.last_name as last_name,
a.address_state as state
from cnx_contact as c
inner join cnx_address as a on c.home_address_uid = a.address_uid
where a.address_state = 'OH'
and (c.orgid = 45 or c.orgid = 55)
and c.contact_id NOT IN (
select pc.contact_id
from cnx_contact as c
inner join cnx_address as a on c.home_address_uid = a.address_uid
inner join cnx_contact_group_participant as gp on c.contact_id = gp.contact_id
inner join cnx_contact_participant_role as cr on gp.participant_role_uid = cr.participant_role_uid
inner join cnx_contact_group as cg on gp.group_uid = cg.group_uid
inner join cnx_contact_group_participant as pgp on cg.primary_participant_uid = pgp.participant_uid
inner join cnx_contact as pc on pgp.contact_id = pc.contact_id
where (c.orgid = 45 or c.orgid = 55)
and cr.name = 'Applicant'
);
select
c.columns
from cnx_contact as c
inner join cnx_address as a on c.home_address_uid = a.address_uid
LEFT JOIN
(Subquery goes here) x
ON x.contact _id = c.contact_id
where a.participant_state = 'OH'
and c.orgid IN(45,55)
and x.contact_id IS NULL;
I'm trying to update the fields by using below query. What is the error in below query ?
MySQL said: Documentation
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 'FROM orders cl' at line 2
update hedging SET
Dept = concat(RIGHT( dpt.DeptName,2),LEFT( grp.GroupName,3),LEFT( st.Login,3)),
OrderNo = cl.OrderNo,Client = cn.ShortName,
Currency = cur.Notation, SellingAmount = pto.PIAmount ,
BuyingAmount = pto.POAmount
FROM orders cl
left join client cn on cl.ClientID = cn.ClientID
inner join department dpt on cl.DeptID = dpt.DeptID
inner join supplier sp on cl.SupplierID = sp.SupplierId
left join staff st on st.StaffID = cl.SalesPerson
left join pipo_total pto on pto.OrderNo = cl.OrderNo
inner join groups grp on cl.GroupID = grp.GroupID
left join currency cur on cur.CurrencyID= cl.SellCurrencyID
left join hedging hed on hed.OrderNo = cl.OrderNo)
where cur.Notation <> 'USD' and cl.OrderType = '1' and hed.OrderNo = cl.OrderNo
Try 1
update orders cl
left join client cn on cl.ClientID = cn.ClientID
inner join department dpt on cl.DeptID = dpt.DeptID
inner join supplier sp on cl.SupplierID = sp.SupplierId
left join staff st on st.StaffID = cl.SalesPerson
left join pipo_total pto on pto.OrderNo = cl.OrderNo
inner join groups grp on cl.GroupID = grp.GroupID
left join currency cur on cur.CurrencyID= cl.SellCurrencyID
left join hedging hed on hed.OrderNo = cl.OrderNo
SET hed.Dept = concat(RIGHT( dpt.DeptName,2),LEFT( grp.GroupName,3),LEFT( st.Login,3))
,hed.OrderNo = cl.OrderNo
,hed.Client = cn.ShortName
,hed.Currency = cur.Notation
,hed.SellingAmount = pto.PIAmount
,hed.BuyingAmount = pto.POAmount
where cur.Notation <> 'USD' and cl.OrderType = '1' and hed.OrderNo = cl.OrderNo
UPDATE with multiple tables should be something like this
UPDATE table1 t1
INNER JOIN table2 t2 ON t1.ID = t2.ID
SET t1.value = [value]
Edit: Your updated query
update orders cl
left join client cn on cl.ClientID = cn.ClientID
inner join department dpt on cl.DeptID = dpt.DeptID
inner join supplier sp on cl.SupplierID = sp.SupplierId
left join staff st on st.StaffID = cl.SalesPerson
left join pipo_total pto on pto.OrderNo = cl.OrderNo
inner join groups grp on cl.GroupID = grp.GroupID
left join currency cur on cur.CurrencyID= cl.SellCurrencyID
left join hedging hed on hed.OrderNo = cl.OrderNo)
SET Dept = concat(RIGHT( dpt.DeptName,2),LEFT( grp.GroupName,3),LEFT( st.Login,3))
,OrderNo = cl.OrderNo
,Client = cn.ShortName
,Currency = cur.Notation
,SellingAmount = pto.PIAmount
,BuyingAmount = pto.POAmount
where cur.Notation <> 'USD' and cl.OrderType = '1' and hed.OrderNo = cl.OrderNo
I've got the query below that's pulling data from a number of tables to create an update:
UPDATE en_inter.subscribers_data AS sd
inner join en_inter.list_subscribers AS ls on sd.subscriberid = ls.subscriberid
LEFT JOIN (
SELECT pd1.email_address,COUNT(pd1.email_address) AS NumDowns
FROM email.papr_down pd1
INNER JOIN email.papr_data pd2 on pd1.paper_id = pd2.id
INNER JOIN email.papr_subj ps on ps.id = pd2.subject
INNER JOIN email.papr_exam pe on pe.id = pd2.exam
INNER JOIN email.papr_levl pl on pl.id = pd2.level
WHERE pd2.exam = 1
and pd2.level = 4
GROUP BY email_address
) AS downs ON downs.email_address = ls.emailaddress
SET sd.data = ifnull(downs.NumDowns,1)
WHERE sd.fieldid = 33;
It works fine but when there are plenty of records in papr_down then it takes ages to process. Any ideas about how it can be optimized?
What I think is the join between the emailAddress is the issue here, you can try out with the join with the Id's.
If you provide us the screen shot of the below query ::
EXPLAIN Select * from
en_inter.subscribers_data AS sd
inner join en_inter.list_subscribers AS ls on sd.subscriberid = ls.subscriberid
LEFT JOIN (
SELECT pd1.email_address,COUNT(pd1.email_address) AS NumDowns
FROM email.papr_down pd1
INNER JOIN email.papr_data pd2 on pd1.paper_id = pd2.id
INNER JOIN email.papr_subj ps on ps.id = pd2.subject
INNER JOIN email.papr_exam pe on pe.id = pd2.exam
INNER JOIN email.papr_levl pl on pl.id = pd2.level
WHERE pd2.exam = 1
and pd2.level = 4
GROUP BY email_address
) AS downs ON downs.email_address = ls.emailaddress
WHERE sd.fieldid = 33
As I know we should use joins only for the columns which are preset in SELECT clause and for other joins we should implement using WHERE clause
Please try following query:
UPDATE en_inter.subscribers_data AS sd
inner join en_inter.list_subscribers AS ls
on sd.subscriberid = ls.subscriberid
LEFT JOIN (
SELECT pd1.email_address,COUNT(pd1.email_address) AS NumDowns
FROM email.papr_down AS pd1
INNER JOIN email.papr_data AS pd2 on pd1.paper_id = pd2.id
WHERE
email.papr_exam.id in (select exam from email.papr_data where exam = 1)
AND
email.papr_levl.id in (select level from email.papr_data where level = 4 )
AND
email.papr_subj.id in (select subject from email.papr_data)
GROUP BY email_address
) AS downs ON downs.email_address = ls.emailaddress
SET sd.data = ifnull(downs.NumDowns,1)
WHERE sd.fieldid = 33;
I can not execute this at my machine since i don't have the schema