仅当行存在在另一个表中时,SQL显示才会结果
如果存在该特定值,则有没有办法显示结果,而另一个表中有多个条目?
例如,我仅在类型是数学时才尝试显示老师的名字。如果没有数学的条目,则专栏老师应该不会显示。
用户名u | 发送电子邮件 |
---|---|
给我 | [email  procected] |
-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ceee3fbccbda2efe3e1">[email protected] |
Classes C | Username |
---|---|
First | Me |
Second | Me |
Third | Me |
Third | Wiz |
Classes | Teacher T | Type |
---|---|---|
First | A | Math |
Second | b | 数学 |
第三 | c | null |
最终结果,因为我存在数学课,
用户名 | 电子邮件 | 老师 |
---|---|---|
我 | ] | a |
me |   prectioned] |
名 | email email | 用户 |
---|---|---|
wiz wiz | 我遇到的问题都不 |
是我的查询即使用户没有数学,但有其他类别,或者它显示数学,也没有同时显示数学,即使我的查询也没有条目。
我当前的查询如下:
from User u
join classes c on c.username=u.username
join teachers t on t.classes=c.classes and type ='Math' <---- If I left join, I get 2 entries, if I join, I get 0 entries for non-math folks
where username ='Me'
因此,我希望查询的3个方案涵盖:
如果用户表中不存在用户(无访问)
如果用户存在但没有任何数学(显示用户无条目)
如果用户存在并且具有数学(无论其他类型如何)显示类 - 那里的最终情况
我会在案例语句中做某种选择吗?此查询是更大的执行查询的一部分。
这是SQL Server Management Studio
Is there a way to display results only if that particular value exists, if there are multiple entries of it in another table?
For example, I am trying to display teacher name only if the type is Math. If there are no entries of Math, the column Teacher should display none.
UserName U | |
---|---|
Me | [email protected] |
Wiz | [email protected] |
Classes C | Username |
---|---|
First | Me |
Second | Me |
Third | Me |
Third | Wiz |
Classes | Teacher T | Type |
---|---|---|
First | A | Math |
Second | B | Math |
Third | C | NULL |
Final result as Math Classes exist for Me
UserName | Teacher | |
---|---|---|
Me | [email protected] | A |
Me | [email protected] | B |
Final result as Math Classes exist for Wiz with no math classes
UserName | Teacher | |
---|---|---|
Wiz | [email protected] | None |
The issue I'm running into is that my query is displaying either no entries even though user has no math but has other classes, or it's displaying Math and None at the same time.
My current query is as follows:
from User u
join classes c on c.username=u.username
join teachers t on t.classes=c.classes and type ='Math' <---- If I left join, I get 2 entries, if I join, I get 0 entries for non-math folks
where username ='Me'
So the 3 scenarios I want the query to cover:
If user does not exist in the user table (no entry)
If user exists but doesn't have any math (show user None entry)
If user exists and has math (regardless of any other type) display classes - final situation up there
Do I do some kind of select count in the case statement? This query is part of a bigger execution query.
This was SQL Server Management Studio
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样的事情会解决您的问题吗?
Would something like this solve your question?
db fiddle