我应该在 SQL 过程中使用游标吗?
我有一个包含计算机登录和注销事件的表。每行都是一个单独的事件,带有时间戳、计算机名称、登录或注销事件代码以及其他详细信息。我需要创建一个 SQL 过程来遍历该表并找到相应的登录和注销事件,并将新行插入到另一个包含计算机名称、登录时间、注销时间和持续时间的表中。
那么,我应该使用光标来执行此操作还是有更好的方法来执行此操作?数据库非常庞大,因此效率肯定是一个问题。任何建议的伪代码也很棒。
[编辑:从评论中提取]
源表:
History (
mc_id
, hs_opcode
, hs_time
)
现有数据解释:
Login_Event = unique mc_id, hs_opcode = 1, and hs_time is the timestamp
Logout_Event = unique mc_id, hs_opcode = 2, and hs_time is the timestamp
I have a table that contains computer login and logoff events. Each row is a separate event with a timestamp, machine name, login or logoff event code and other details. I need to create a SQL procedure that goes through this table and locates corresponding login and logoff event and insert new rows into another table that contain the machine name, login time, logout time and duration time.
So, should I use a cursor to do this or is there a better way to go about this? The database is pretty huge so efficiency is certainly a concern. Any suggested pseudo code would be great as well.
[edit : pulled from comment]
Source table:
History (
mc_id
, hs_opcode
, hs_time
)
Existing data interpretation:
Login_Event = unique mc_id, hs_opcode = 1, and hs_time is the timestamp
Logout_Event = unique mc_id, hs_opcode = 2, and hs_time is the timestamp
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,如果您可以以不需要复杂的子查询来配对行的方式对数据进行排序,那么您的查询将会更简单(并且更快)。由于 MySQL 不支持 CTE 即时执行此操作,因此您需要创建一个临时表:
然后,从原始表中提取并排序到新表中:
您现在可以使用此查询来关联数据:
对于将来的插入,您可以使用如下所示的触发器来自动更新持续时间表:
First, your query will be simpler (and faster) if you can order the data in such a way that you don't need a complex subquery to pair up the rows. Since MySQL doesn't support CTE to do this on-the-fly, you'll need to create a temporary table:
Then, pull and sort from your original table into the new table:
You can now use this query to correlate the data:
For future inserts, you can use a trigger like below to keep your duration table updated automatically:
如果没有您正在处理的任何代码.. 很难看出这种方法是否有用.. 可能在某些情况下您确实需要循环遍历事物.. 在某些情况下这种方法可以使用代替..
[编辑:基于海报的评论]
你可以尝试执行这个并看看你是否得到了想要的结果?
Without any code that you're working on.. it'll be hard to see if this approach will be any useful.. There may be some instances when you really need to loop through things.. and some instances when this approach can be used instead..
[EDIT: based on poster's comment]
Can you try executing this and see if you get the desired results?