T-SQL 从表 A 中选择全部并在表 B 上条件
TableA Columns: A_ID, NAME, SOURCE, TITLE, EVENTID
TableB Columns: B_ID, EVENTID, CODE, FIELD
如何提取 NAME、SOURCE、TITLE 和 FIELD 或 null(如果有 CODE=x)?例子应该能更好地说明这一点。它是 SQL Server Express 上的 T-SQL。
示例:
TableA | TableB
-----------------------------------------------------------------------
A_ID, NAME, SOURCE, TITLE, EVENTID | B_ID, EVENTID, CODE, FIELD
-----------------------------------------------------------------------
1 john s1 x 100 | 1 100 5 textA
2 bruce s2 y 105 | 2 100 10 textB
3 bob s3 z 110 | 3 105 5 textC
| 4 110 5 textD
| 5 110 10 textE
EventId 105 没有代码 10,因此结果应为 null。如何编写一个 SELECT 查询来给我这样的结果:
[ john | s1 | x | textB ]
[ bruce | s2 | y | ]
[ bob | s3 | z | textE ]
这可能真的很容易,但我无法弄清楚..提前致谢。
TableA Columns: A_ID, NAME, SOURCE, TITLE, EVENTID
TableB Columns: B_ID, EVENTID, CODE, FIELD
How do I extract NAME, SOURCE, TITLE and FIELD or null (if there is CODE=x) ? Example should show it better. It's T-SQL on SQL Server Express.
Example:
TableA | TableB
-----------------------------------------------------------------------
A_ID, NAME, SOURCE, TITLE, EVENTID | B_ID, EVENTID, CODE, FIELD
-----------------------------------------------------------------------
1 john s1 x 100 | 1 100 5 textA
2 bruce s2 y 105 | 2 100 10 textB
3 bob s3 z 110 | 3 105 5 textC
| 4 110 5 textD
| 5 110 10 textE
There is no code 10 for EventId 105 so the result should be null. How do write a SELECT quesry that would give me such result:
[ john | s1 | x | textB ]
[ bruce | s2 | y | ]
[ bob | s3 | z | textE ]
It might be really easy but I can't figure it out.. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在表之间使用
OUTER JOIN
B.CODE = 10
条件需要进入JOIN
而不是WHERE 子句,以避免有效地将查询转回
INNER JOIN
。如果有多个连接记录,这可能会为特定的
A
值返回多行,但从您的问题中不清楚这在您的数据中是否可能(如果是的话,哪个B .Field
值应该被使用),这很可能是您想要的行为。You need an
OUTER JOIN
between the tablesThe
B.CODE = 10
condition needs to go in theJOIN
not aWHERE
clause to avoid effectively turning the query back into anINNER JOIN
.This can return multiple rows for a particular
A
value if there is more than one joining record but it is not clear from your question if this is possible in your data anyway (and if so whichB.Field
value should be used) and this may well be your desired behaviour.这应该可以做到
This should do it