0

I have a table which stores "active" users of some arbitrary facility. There is an insert operation for every time a particular user logs on and logs off. What I want to be able to do is as follows:

  • Upon detection of an insert operation into the database, check if the username is already present in the MYSQL database.
  • If the username is present, then do not insert and delete the existing entry.
  • If the username is not present, then insert.

Is there any way to achieve this? I am fairly new to MYSQL so I apologize in advance if anything I've said doesn't make sense - just ask for my clarification.

bawse
  • 201
  • 3
  • 13

1 Answers1

0

What I want to be able to do is as follows:

  • Upon detection of an insert operation into the database, check if the username is already present in the MYSQL database.

Yes, you can achieve this

  • If the username is present, then do not insert and delete the existing entry.

You can manually search the username, and do the condition-statement as you want.

  • If the username is not present, then insert.

Same thing.

Here's an example base from what you want:

--INPUT @Username

IF EXISTS(SELECT * FROM activeUsers WHERE Username = @Username) THEN

    DELETE FROM activeUsers WHERE Username = @Username

ELSE

    INSERT INTO activeUsers (columns...) VALUES (values)

END IF
KaeL
  • 3,639
  • 2
  • 28
  • 56
  • Thanks for the answer. If I were to add a couple more columns to the table for additional information, will your example still work? Or will it need to be altered? – bawse Dec 10 '15 at 02:45
  • It depends on the design of your tables and in your requirements. If we will still use `Username` as basis for not inserting new ones in the `activeUsers` table, then there will not be any problem. – KaeL Dec 10 '15 at 02:48
  • Another question, if I'm inserting values from syslog-ng into the mysql database, then where exactly would i put your above configuration? – bawse Dec 10 '15 at 20:11
  • You said that `There is an insert operation for every time a particular user logs on and logs off.`, you might need to *tweak* that a bit. – KaeL Dec 11 '15 at 02:19