snippetModerate
How to get all records from one table and see if they are used in another without a sub query
Viewed 0 times
withoutallareusedrecordsquerysubseeoneget
Problem
I'm trying to write a SQL statement that pulls down all the records from one table and looks to see if they are used in another. SQL is not my strongest language, so I'm sure this is a pretty simple query. Here are my two tables:
A user can apply any number of contracts to an order, so what I need to do is get a list of all the contracts, and see if they are used in a particular order. Right now, I use a sub query to get the job done, but I don't like using sub queries if I don't need to.
Ideally I'd like to get a result set that looks like this where if value is NULL in the OrderID column, that means it's not used:
Any help is greatly appreciated. Thanks!
tblOrderContracts
--------------------------------------
OrderContractID | bigint
OrderID | bigint
UserContractID | bigint
UserName | varchar
OrderContractDateCreated | datetime
OrderContractStatus | varchar
tblUserContracts
-------------------------------------
UserContractId | bigint
UserName | varchar
UserContractName | varchar
UserContractFileName | varchar
UserContractDateCreated | datetime
UserContractStatus | varcharA user can apply any number of contracts to an order, so what I need to do is get a list of all the contracts, and see if they are used in a particular order. Right now, I use a sub query to get the job done, but I don't like using sub queries if I don't need to.
SELECT uc.UserContractId, uc.UserContractName,
(SELECT oc.OrderID FROM tblOrderContracts as oc WHERE uc.UserContractID =
oc.UserContractID AND oc.OrderID = 466 AND OrderContractStatus =
'Active')
FROM tblUserContracts as uc
WHERE uc.UserName = 'vandel212' AND UserContractStatus = 'Active'Ideally I'd like to get a result set that looks like this where if value is NULL in the OrderID column, that means it's not used:
UserContractId | UserContractName | OrderID
-----------------------------------------------
36 | test | 466
37 | test2 | NULL
38 | test3 | NULLAny help is greatly appreciated. Thanks!
Solution
You can use a
LEFT JOIN to get the same results. Note how the WHERE condition of the subquery was moved to the ON clause of the join:SELECT
uc.UserContractId,
uc.UserContractName,
oc.OrderID
FROM
tblUserContracts AS uc
LEFT JOIN tblOrderContracts AS oc
ON uc.UserContractID = oc.UserContractID
AND oc.OrderID = 466
AND oc.OrderContractStatus = 'Active'
WHERE
uc.UserName = 'vandel212'
AND uc.UserContractStatus = 'Active' ;Code Snippets
SELECT
uc.UserContractId,
uc.UserContractName,
oc.OrderID
FROM
tblUserContracts AS uc
LEFT JOIN tblOrderContracts AS oc
ON uc.UserContractID = oc.UserContractID
AND oc.OrderID = 466
AND oc.OrderContractStatus = 'Active'
WHERE
uc.UserName = 'vandel212'
AND uc.UserContractStatus = 'Active' ;Context
StackExchange Database Administrators Q#186781, answer score: 13
Revisions (0)
No revisions yet.