简体   繁体   中英

SQL Select All Without Values in Another Table

I'm building an application to manage tools that are on loan to staff members and the way that the table is set up is there has a Tools table which has a unique tool code and serial number and a Loans table that contains the unique tool code and a return date. Each time there is a loan, it creates a new entry, the return date when the loan is created is null.

The query I have at the moment searches for all tools based on a text input. I've tried a lot of code with inner joins with no success and as I'm not extremely experienced with SQL, I couldn't figure out how to make it work.

SELECT [Tools].[ToolID], [Tools].[Type], [Tools].[Brand], [Tools].[Serial], [Tools].[Year], [Tools].[Code] FROM [Tools]
WHERE ([Tools].Serial LIKE '%234%' OR [Tools].Code LIKE '%234%') 

My issue occurs when I'm searching for a tool in the loan database. I want it to show tools from the Tools table that:

A) Have no entries in the loan database (ie a new tool)

B) All entries in the database have a return date (tool has been returned)

Thanks.

EDIT: Combined the two queries from the answer

SELECT [Tools].[ToolID], [Tools].[Type], [Tools].[Brand], [Tools].[Serial], [Tools].[Year], [Tools].[Code] 
FROM [Tools] left outer join
Loan ON [Tools].code = Loan.toolcode
WHERE Loan.toolcode is null AND ([Tools].Code LIKE '%234%' OR [Tools].Serial LIKE '%234%')

UNION

SELECT [Tools].[ToolID], [Tools].[Type], [Tools].[Brand], [Tools].[Serial], [Tools].[Year], [Tools].[Code]
FROM Loan
INNER JOIN Tools ON Tools.Code = Loan.ToolCode
GROUP BY [Tools].[ToolID], [Tools].[Type], [Tools].[Brand], [Tools].[Serial], [Tools].[Year], [Tools].[Code]
HAVING count(returndate) = count(*)

To show tools that have no entry in the loan database:

SELECT t.*
from tools t left outer join
     loans l
     on t.code = l.toolcode WHERE l.toolcode is null;

I assume that for the second question, you want all tools where all entries have a return date -- that is, no entry is NULL :

select l.toolcode
from loans l
group by l.toolcode
having sum(case when returndate is null then 1 else 0 end) = 0

This formulation counts up the number of records where the returndate is null and only returns tools where there are no such records. An alternative way of writing the same logic is:

having count(returndate) = count(*)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM