对选择值使用内部选择结构
我想听听是否有人可以告诉我一个简单的语法,它可以实现与以下相同的功能(具有相同的灵活性):
SELECT C.CompanyName,
(SELECT Count(*) FROM Employees WHERE CompanyId = C.Id) as EmployeeCount
FROM Company C
现在,重要的是给出 EmployeeCount 的内部 SELECT 是:
- 一个独立的 SELECT 语句
- 这意味着它应该适用于任何现有的 SELECT,即使它已经包含联接等。
- 可以使用父 SELECT 中的值
我知道这种情况可以通过其他方式轻松完成,但上面是一个简化的示例解释挑战。我的真实场景是一个复杂的 SELECT 语句,我不想通过添加更多联接来使其复杂化。性能没有问题。
I would like to hear if anyone can tell me a simple syntax that accomplishes the same as the following (with the same flexibility):
SELECT C.CompanyName,
(SELECT Count(*) FROM Employees WHERE CompanyId = C.Id) as EmployeeCount
FROM Company C
Now, what's important is that the inner SELECT giving the EmployeeCount is:
- An independent SELECT statement
- This means that it should work with any existing SELECT, even if it already contains joins etc.
- Can use values from the parent SELECT
I know that this scenario can be easily accomplished in other ways, but the above is a simplified example to explain the challenge. My real scenario is a complex SELECT statement where I do not want to complicate it by adding more joins. Performance is no issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
INNER JOIN
:使用
NESTED JOIN
:如果你想使用相同的语法,至少这样写:
如果你需要显示所有数据,甚至是那些数据没有任何员工的公司,您可以使用
LEFT OUTER JOIN
:Using
INNER JOIN
:Using
NESTED JOIN
:If you want to use the same syntax, at least put this:
If you need all the data to be shown, even the ones the companies without any Employees, you can use a
LEFT OUTER JOIN
:尝试使用派生表,它可以统计您的两个条件。
独立的 SELECT 语句。
一个。使用派生表可以让您保留独立的 Select 语句
可以使用父 SELECT 中的值。
a.作为内部联接,您仍然可以使用父级选择中的值。
Try using a derived table, which statifies both your conditions.
An independent SELECT statement.
a. Using a Derived Table allows you to keep your independent Select Statement
Can use values from the parent SELECT.
a. As an Inner join you can still use values from the parent select.
如果您的内部选择很复杂,那么为什么不对其进行查看:
然后
If your inner select is complicated, then why not make a view of it:
Then