hizki
hizki

Reputation: 719

Filter MySQL table using data from another table

I have one table containing "user sessions" and another to indicate violations in the system. One possible violation is having a user logged on for more than 12 hours straight.

The tables are as followed:

notification:
+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| id           | int(11)     | NO   | PRI | NULL    | auto_increment |
| host_id      | int(11)     | NO   | MUL | NULL    |                |
| alert_id     | int(11)     | NO   | MUL | NULL    |                |
| event_start  | datetime    | NO   |     | NULL    |                |
| time_noticed | datetime    | NO   |     | NULL    |                |
| info         | varchar(45) | YES  |     | NULL    |                |
| seen         | int(11)     | NO   |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+

login:
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(45) | NO   |     | NULL    |       |
| host_id  | int(11)     | NO   | MUL | NULL    |       |
| start    | datetime    | NO   |     | NULL    |       |
| end      | datetime    | NO   |     | NULL    |       |
| last     | int(11)     | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+

The conditions I want for the result table are:
login.last = 1, login.host_id=X, end>start+12hours
and to make sure I didn't report this instance before:
login.host_id!=notification.host_id, notification.alert_id!=Y, login.start!=notification.event_start, login.username!=notification.info
(in other words, I don't want to get another report of the same user, on the same host, making the same violation which started at the same time)

Upvotes: 1

Views: 1699

Answers (1)

eplaut
eplaut

Reputation: 36

SELECT DISTINCT username, start 
FROM login 
LEFT OUTER JOIN notification ON 
    (login.host_id = notification.host_id 
    AND login.start = notification.event_start
    AND login.username = notification.info) 
WHERE 
    end>DATE_ADD(start,INTERVAL 12 HOUR) 
    AND login.host_id=$host_id 
    AND last=1 
    AND login.id IS NULL

This query should use "not exist" type of search (try EXPLAIN) which is good for the query performance. maybe it worth to put UNIQUE KEY on notification 'host_id,event_started,info' and use INSERT IGNORE

Upvotes: 2

Related Questions