время в базе данных MySQL в течение определенного периода времени

0

поэтому я пытаюсь получить средние значения в течение 20-минутного периода и добавить его из моей основной таблицы sql в дополнительную таблицу, номер будет заходить в базу данных несколько раз в течение дня, и он хорошо работает в первый раз, когда номер идет, но тогда, если он появится позднее в тот же день, когда обновит вторичную таблицу до гораздо более высокого значения, например

номер 58 отправляется в 12:08, а затем останавливается в 12:31. avg покажет 23 минуты, если он вернется в стол в 13:47 и выйдет в 14:13 вечера, он покажет 2 часа и 5 минут

im в настоящее время использует

insert into test.time (beacon,location,date,time_avg,mac,time)
SELECT beacon,location,date, 
TIMEDIFF(max('time'),min('time')) AS 'time_avg',mac,time
FROM test.test where time > now() - interval 30 minute
group by beacon
ORDER BY 'time_avg' DESC

как я могу запросить его так, чтобы он добавлял новую строку в течение получаса или около того, я пытался использовать событие, где он запрашивал его только каждые 30 минут, а не после каждого обновления, но я все еще получал ту же проблему, у меня также есть попытался вставить игнорировать, где mac является уникальным значением и заменить на.

Я прикрепил изображение моей таблицы, чтобы дать представление о данных, которые находятся в нем.

примеры данных в строке для удобства

insert into test ('location','beacon','mac','date','time') VALUES (YELLOW, 1,AC3422845D, 2018-01-10, 12:08:55);

данные таблицы mysql

  • 0
    Мы не можем использовать изображения, вы можете добавить свои образцы данных в виде текста к вопросу.
  • 0
    Если я вас правильно понимаю, каждый маяк / местоположение / mac / date имеет неизвестное количество раз, вы хотите рассчитать разницу во времени для фрагментов времени, которые попадают в 20-минутные интервалы, и усреднить их по количеству фрагментов в день (так далеко). Когда вы начнете И закончите эти 20-минутные куски (00:00 - 24:00?)
Показать ещё 2 комментария
Теги:

1 ответ

0

У вас есть несколько вещей, на которые можно посмотреть и, возможно, исправить в вашей вставке... выберите. Если ваша цель состоит в том, чтобы иметь 1 запись в таблице вставки для маяка, mac, date, тогда вставка на дубликат ключа, вероятно, вы хотите. Например

MariaDB [песочница]> отбрасывать таблицу, если существует t; Запрос ОК, 0 строк затронуты (0,27 с)

MariaDB [sandbox]>
MariaDB [sandbox]> create table t
    -> (location varchar(20),beacon int, mac varchar(20),'date' date, 'time' time);
Query OK, 0 rows affected (0.20 sec)

MariaDB [sandbox]> insert into t (location,beacon,mac,'date','time') VALUES ('YELLOW', 1,'AC3422845D', '2018-01-10', '11:00:44');
Query OK, 1 row affected (0.01 sec)

MariaDB [sandbox]> insert into t (location,beacon,mac,'date','time') VALUES ('YELLOW', 1,'AC3422845D', '2018-01-11', '10:00:55');
Query OK, 1 row affected (0.01 sec)

MariaDB [sandbox]> insert into t (location,beacon,mac,'date','time') VALUES ('YELLOW', 1,'AC3422845D', '2018-01-11', '11:00:55');
Query OK, 1 row affected (0.05 sec)

MariaDB [sandbox]> insert into t (location,beacon,mac,'date','time') VALUES ('YELLOW', 1,'AC3422845D', '2018-01-11', '12:00:55');
Query OK, 1 row affected (0.02 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> drop table if exists t1;
Query OK, 0 rows affected (0.08 sec)

MariaDB [sandbox]> create table t1
    -> (beacon int,location varchar(20), mac varchar(20),'date' date, maxtimetime  time, mintime time, obs int, now30 datetime);
Query OK, 0 rows affected (0.26 sec)

MariaDB [sandbox]> alter table t1
    -> add unique key  t1k1 (beacon,mac,'date');
Query OK, 0 rows affected (0.18 sec)
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]>
MariaDB [sandbox]> #select * from t;
MariaDB [sandbox]> #select @now;
MariaDB [sandbox]>
MariaDB [sandbox]> truncate table t1;
Query OK, 0 rows affected (0.27 sec)

MariaDB [sandbox]> set @now = str_to_date('2018-01-10 11:15:00','%Y-%m-%d %H:%i:%s');
Query OK, 0 rows affected (0.00 sec)

MariaDB [sandbox]> insert into t1 (beacon ,mac ,'date', maxtimetime, mintime, obs, now30)
    -> select *
    -> from
    -> (select t.beacon,t.mac,t.'date', max('time') maxtime,min('time') mintime,count(*) obs,
    -> @now - interval 30 minute now30
    -> from t
    -> where 'time'  between time(@now - interval 30 minute) and time(@now) and 'date' = date(@now)
    -> group by t.beacon ,t.mac,t.'date'
    -> ) s
    -> on duplicate key
    -> update maxtimetime = s.maxtime, mintime = s.mintime, obs = s.obs, now30 = s.now30;
Query OK, 1 row affected (0.03 sec)
Records: 1  Duplicates: 0  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]> select * from t1;
+--------+----------+------------+------------+-------------+----------+------+---------------------+
| beacon | location | mac        | date       | maxtimetime | mintime  | obs  | now30               |
+--------+----------+------------+------------+-------------+----------+------+---------------------+
|      1 | NULL     | AC3422845D | 2018-01-10 | 11:00:44    | 11:00:44 |    1 | 2018-01-10 10:45:00 |
+--------+----------+------------+------------+-------------+----------+------+---------------------+
1 row in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> set @now = str_to_date('2018-01-11 11:15:00','%Y-%m-%d %H:%i:%s');
Query OK, 0 rows affected (0.00 sec)

MariaDB [sandbox]> insert into t1 (beacon ,mac ,'date', maxtimetime, mintime, obs, now30)
    -> select *
    -> from
    -> (select t.beacon,t.mac,t.'date', max('time') maxtime,min('time') mintime,count(*) obs,
    -> @now - interval 30 minute now30
    -> from t
    -> where 'time' between time(@now - interval 30 minute) and time(@now) and 'date' = date(@now)
    -> group by t.beacon ,t.mac,t.'date'
    -> ) s
    -> on duplicate key
    -> update maxtimetime = s.maxtime, mintime = s.mintime, obs = s.obs, now30 = s.now30;
Query OK, 1 row affected (0.03 sec)
Records: 1  Duplicates: 0  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]> select * from t1;
+--------+----------+------------+------------+-------------+----------+------+---------------------+
| beacon | location | mac        | date       | maxtimetime | mintime  | obs  | now30               |
+--------+----------+------------+------------+-------------+----------+------+---------------------+
|      1 | NULL     | AC3422845D | 2018-01-10 | 11:00:44    | 11:00:44 |    1 | 2018-01-10 10:45:00 |
|      1 | NULL     | AC3422845D | 2018-01-11 | 11:00:55    | 11:00:55 |    1 | 2018-01-11 10:45:00 |
+--------+----------+------------+------------+-------------+----------+------+---------------------+
2 rows in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> set @now = str_to_date('2018-01-11 12:15:00','%Y-%m-%d %H:%i:%s');
Query OK, 0 rows affected (0.00 sec)

MariaDB [sandbox]> insert into t1 (beacon ,mac ,'date', maxtimetime, mintime, obs, now30)
    -> select *
    -> from
    -> (select t.beacon,t.mac,t.'date', max('time') maxtime,min('time') mintime,count(*) obs,
    -> @now - interval 30 minute now30
    -> from t
    -> where 'time'  between time(@now - interval 30 minute) and time(@now) and 'date' = date(@now)
    -> group by t.beacon ,t.mac,t.'date'
    -> ) s
    -> on duplicate key
    -> update maxtimetime = s.maxtime, mintime = s.mintime, obs = s.obs, now30 = s.now30;
Query OK, 2 rows affected (0.02 sec)
Records: 1  Duplicates: 1  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]> select * from t1;
+--------+----------+------------+------------+-------------+----------+------+---------------------+
| beacon | location | mac        | date       | maxtimetime | mintime  | obs  | now30               |
+--------+----------+------------+------------+-------------+----------+------+---------------------+
|      1 | NULL     | AC3422845D | 2018-01-10 | 11:00:44    | 11:00:44 |    1 | 2018-01-10 10:45:00 |
|      1 | NULL     | AC3422845D | 2018-01-11 | 12:00:55    | 12:00:55 |    1 | 2018-01-11 11:45:00 |
+--------+----------+------------+------------+-------------+----------+------+---------------------+
2 rows in set (0.00 sec)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню