[英]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.
我已经尝试了很多带有内部联接的代码,但是都没有成功,而且由于我对SQL的经验不是很丰富,所以我不知道如何使它起作用。
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) A)贷款数据库中没有条目(即新工具)
B) All entries in the database have a return date (tool has been returned) B)数据库中的所有条目都有返回日期(工具已返回)
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
: 我假设对于第二个问题,您需要所有条目都有返回日期的所有工具-也就是说,没有条目为
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. 此公式对
returndate
为null
的记录数进行returndate
,仅返回没有此类记录的工具。 An alternative way of writing the same logic is: 编写相同逻辑的另一种方法是:
having count(returndate) = count(*)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.