[英]SQL - Looping through ever row of table in mysql?
所以我有2張桌子, communication
和movement
。
communication
具有fromID
列,具有呼叫者ID的timestamp
和呼叫時間。 然后,我進行了另一個表movement
,該表movement
具有ID
, timestamp
, x
, y
,具有一個人的ID,他們的位置(x,y)
以及他們在該位置的時間。
我想寫一個看起來像這樣的查詢:
For every single row of communication(R)
SELECT * FROM movement m
WHERE m.ID = R.fromID && m.timestamp <= R.timestamp
ORDER BY timestamp
基本上,這是為給定的communication timestamp
找到最接近的movement timestamp
communication timestamp
。 之后,最終,我想根據movement
數據找到呼叫的位置(x,y)
。
我該怎么做? 我知道有一種基於集合的方法,但是我不想那樣做。 我看着cursors
,但是我感到在那方面的表現很糟糕……所以無論如何都要循環執行此操作? 我本質上是想遍歷communication
每一行,並得到結果...
我嘗試過這樣的事情:
DELMITER $$
CREATE PROCEDURE findClosestTimestamp()
BEGIN
DECLARE commRowCount DEFAULT 0;
DECLARE i DEFAULT 0;
DECLARE ctimestamp DEFAULT 0;
SELECT COUNT(*) FROM communication INTO commRowCount;
SET i = 0;
WHILE i < commRowCount DO
SELECT timestamp INTO ctimestamp FROM communication c
SELECT * FROM movement m
WHERE m.vID = c.fromID && m.timestamp <= R.timestamp
END$$
DELIMITER ;
但是我知道那是完全錯誤的……是做這種游標的唯一方法嗎? 我只是在Internet上的任何地方都找不到這樣的示例,而且我對SQL過程完全陌生。 任何指導將不勝感激,謝謝!!
讓我們看看我是否可以使用光標將您指向正確的方向:
delimiter $$
create procedure findClosestTimeStamp()
begin
-- Variables to hold values from the communications table
declare cFromId int;
declare cTimeStamp datetime;
-- Variables related to cursor:
-- 1. 'done' will be used to check if all the rows in the cursor
-- have been read
-- 2. 'curComm' will be the cursor: it will fetch each row
-- 3. The 'continue' handler will update the 'done' variable
declare done int default false;
declare curComm cursor for
select fromId, timestamp from communication; -- This is the query used by the cursor.
declare continue handler for not found -- This handler will be executed if no row is found in the cursor (for example, if all rows have been read).
set done = true;
-- Open the cursor: This will put the cursor on the first row of its
-- rowset.
open curComm;
-- Begin the loop (that 'loop_comm' is a label for the loop)
loop_comm: loop
-- When you fetch a row from the cursor, the data from the current
-- row is read into the variables, and the cursor advances to the
-- next row. If there's no next row, the 'continue handler for not found'
-- will set the 'done' variable to 'TRUE'
fetch curComm into cFromId, cTimeStamp;
-- Exit the loop if you're done
if done then
leave loop_comm;
end if;
-- Execute your desired query.
-- As an example, I'm putting a SELECT statement, but it may be
-- anything.
select *
from movement as m
where m.vID = cFromId and m.timeStamp <= cTimeStamp
order by timestampdiff(SECOND, cTimeStamp, m.timeStamp)
limit 1;
end loop;
-- Don't forget to close the cursor when you finish
close curComm;
end $$
delimiter ;
參考文獻:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.