优化 Oracle SQL 查询
这是我的一个查询,它返回员工的主管链,但它使用了一堆嵌套的 SELECT 语句。 我想知道这个查询是否可以重构以提高效率。该查询针对一个应用程序,其中 3 个级别的管理层授权员工参加培训课程。目前我们需要 3 级批准,但这可能会更改为 4 级或更多。
SELECT badge as employee,
supervisor_badge as boss1,
(select supervisor_badge FROM hr_data level2 WHERE badge = level1.supervisor_badge) as boss2
(select supervisor_badge FROM hr_data level3 WHERE badge =
(select supervisor_badge FROM hr_data level2 WHERE badge = level1.supervisor_badge)) as boss3
FROM hr_data level1 WHERE BADGE = '123456';
徽章 = 员工 ID
Supervisor_badge = 员工主管的徽章
Bothe 字段位于 hr_data 表
badge supervisor_badge
123456 111111
111111 454545
454545 332211
输出中
employee boss1 boss2 boss3
123456 111111 454545 332211
Here is a query I have that returns the chain of supervisors for an employee but it uses a bunch of nested SELECT statements.
I'd like to know whether this query could be refactored to be more efficient. The query is for an application where 3 levels of management authorize an employee to take a training class. Currently we require 3 levels of approvals, but this could change to 4 or more.
SELECT badge as employee,
supervisor_badge as boss1,
(select supervisor_badge FROM hr_data level2 WHERE badge = level1.supervisor_badge) as boss2
(select supervisor_badge FROM hr_data level3 WHERE badge =
(select supervisor_badge FROM hr_data level2 WHERE badge = level1.supervisor_badge)) as boss3
FROM hr_data level1 WHERE BADGE = '123456';
badge = the employee's ID
supervisor_badge = the badge of the employee's supervisor
bothe fields are in the hr_data table
badge supervisor_badge
123456 111111
111111 454545
454545 332211
output
employee boss1 boss2 boss3
123456 111111 454545 332211
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我没有方便的数据库来模拟这个,所以我会即兴发挥。为了清楚起见,我尝试使用相同的命名约定。
重要提示:这只会返回所有连接处都存在数据的记录。要返回少于 3 个老板的记录(即只有老板 1 和老板 2,但没有老板 3),请将 INNER JOIN 语句更改为 LEFT JOIN。
I don't have a database handy, to mock this up, so I'll wing it. I tried to use your same naming conventions, for clarity.
IMPORTANT NOTE: This will only return records where data exists at all joins. To return records that have fewer than 3 bosses (i.e. only boss1 and boss2, but no boss3), change the INNER JOIN statements to LEFT JOIN.
使用连接而不是子查询。
由于级别是可变的,您可能需要考虑使用存储过程在内部循环预先指定的级别数(直到到达顶部,例如您的 CEO)。
Use joins rather than subqueries.
As the level is variable, you may want to consider using a Stored Procedure to internally loop for the prespecified number of levels (until it hits the top, e.g., your CEO).