6

我是 MySQL 新手,需要您的帮助。我有一张包含类似数据的表格

---------------------------------------------------
|RobotPosX|RobotPosY|RobotPosDir|RobotShortestPath|
---------------------------------------------------
|0.1      |   0.2   |      15   |       1456      |
|0.2      |   0.3   |      30   |       1456      |
|0.54     |   0.67  |      15   |       1456      |
|0.68     |   0.98  |      22   |       1234      |
|0.36     |   0.65  |      45   |       1234      |
|0.65     |   0.57  |      68   |       1456      |
|0.65     |   0.57  |      68   |       2556      |
|0.79     |   0.86  |      90   |       1456      |                 
---------------------------------------------------

如您所见,RobotShortestPath 列中有重复的值,但它们很重要。每个数字代表一个特定的任务。如果数字连续重复(例如:1456),则表示机器人正在执行该任务,而当数字发生变化(例如:1234)时,则表示已切换到另一个任务。如果之前的数字(例如:1456)再次出现,这也意味着机器人在完成之前的任务(1234)后正在执行新的任务(1456)。

所以我卡住的地方是我无法完成任何任务。我已经使用了我最基本的知识中的一些东西,比如 COUNT、GROUP BY,但似乎没有任何效果。

这里执行的任务数实际上是 5,但无论我做什么,我只得到 3 个结果。

4

4 回答 4

3
SET @last_task = 0;
SELECT SUM(new_task) AS tasks_performed
FROM (
  SELECT 
    IF(@last_task = RobotShortestPath, 0, 1) AS new_task,
    @last_task := RobotShortestPath
  FROM table
  ORDER BY ??
) AS tmp

更新多个表
从数据库结构规范化视图中,您最好使用一个表,并有一个文件来标识哪个列是哪个机器人,如果由于某种原因这不可行,您可以通过合并表来获得:

SET @last_task = 0;
SELECT robot_id, SUM(new_task) AS tasks_performed
FROM (
  SELECT 
    IF(@last_task = RobotShortestPath, 0, 1) AS new_task,
    @last_task := RobotShortestPath
  FROM (
    SELECT 1 AS robot_id, robot_log_1.* FROM robot_log_1
    UNION SELECT 2, robot_log_2.* FROM robot_log_2
    UNION SELECT 3, robot_log_3.* FROM robot_log_3
    UNION SELECT 4, robot_log_4.* FROM robot_log_4
    UNION SELECT 5, robot_log_5.* FROM robot_log_5
  ) as robot_log
  ORDER BY robot_id, robot_log_id
) AS robot_log_history
GROUP BY robot_id
ORDER BY tasks_performed DESC
于 2012-07-20T09:55:20.757 回答
0

据我了解,您需要跟踪何时RobotShortestPath更改为另一个值。为此,您可以像这样使用触发器

delimiter |

CREATE TRIGGER track AFTER UPDATE ON yourtable
  FOR EACH ROW BEGIN
    IF NEW.RobotShortestPath != OLD.RobotShortestPath THEN
      UPDATE tracktable SET counter=counter+1 WHERE tracker=1;
    END IF;
  END;
|

delimeter ;
于 2012-07-20T09:57:20.600 回答
0
set @n:=0, @i:=0;
select max(sno) from
(
select @n:=case when @i=RobotShortestPath then @n else @n+1 end as sno, 
@i:=RobotShortestPath as dno
from table 
) as t;
于 2012-07-20T09:59:10.507 回答
0

尝试以下查询:

SET @cnt = 0, @r = -1;

SELECT IF(armed <> @r, @cnt:= @cnt + 1, 0), @r:= RobotShortestPath, @cnt FROM table;

SELECT @cnt AS count;
于 2012-07-20T09:59:39.600 回答