1

I have a SELECT query which returns all matching rows added between 12 and 16 hours ago. It may return 0, 1, or multiple rows.

SELECT
  service,
  service_host_name,
  time,
  reports_added
FROM
  detections
WHERE
  reports_added = 0
  AND time BETWEEN DATE_SUB(NOW(), INTERVAL 16 HOUR)
  AND DATE_SUB(NOW(), INTERVAL 12 HOUR);
+---------------+-------------------+---------------------+---------------+
| service       | service_host_name | time                | reports_added |
+---------------+-------------------+---------------------+---------------+
| instagram.com | instagram         | 2020-10-29 08:41:25 |             1 |
| instagram.com | instagram         | 2020-10-29 08:41:25 |             0 |   
| twitter.com   | twitter           | 2020-10-29 03:41:25 |             0 |
| twitter.com   | twitter           | 2020-10-28 17:00:11 |             0 |
| twitter.com   | twitter           | 2020-10-29 15:01:14 |             0 |
| instagram.com | instagram         | 2020-10-29 22:04:23 |             0 |
+---------------+-------------------+---------------------+---------------+

I need to use the matching row(s) from the above query as parameters in the below INSERT... SELECT query.

INSERT
  IGNORE INTO my_detections (
    service,
    service_host_name,
    date
  ) (
    SELECT
      service,
      service_host_name,
      date
    FROM
      report_issue
      INNER JOIN report_domain ON report_issue.issue_id = report_domain.id
    WHERE
      service = service
      AND date BETWEEN DATE_SUB(time, INTERVAL 12 HOUR)
      AND DATE_ADD(time, INTERVAL 12 HOUR)
  )
UNION
(
  SELECT
    service,
    service_host_name,
    date
  FROM
    report_recent
  WHERE
    service = service
    AND date BETWEEN DATE_SUB(time, INTERVAL 12 HOUR)
    AND DATE_ADD(time, INTERVAL 12 HOUR)
);

All the above queries work well on their own.

Ideally, I would also like to UPDATE the reports_added column in the detections table to 1 after the INSERT... SELECT finishes with the corresponding row.

If that's not possible I can just UPDATE after completion e.g

update
  detections
set
  reports_added = 1
where
  reports_added = 0;

How can I use the matching rows from the detections table as parameters for the INSERT... SELECT query?

Eventually, I will be adding the whole query inside a mysql-event running once per hour, so it would be great if the answers were inside an event, but not strictly neccasary as I should be fine with that myself.

turrican_34
  • 679
  • 1
  • 7
  • 27

0 Answers0