tags:

views:

420

answers:

6

I'm using MySQL in particular, but I'm hoping for a cross-vendor solution. I'm using the NOW() function to add a timestamp as a column for each record.

INSERT INTO messages 
(typeId, messageTime, stationId, message) 
VALUES 
(?, NOW(), ?, ?)
+4  A: 
SELECT * FROM messages WHERE DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= messageTime
Alexander Morland
Which vendor does this syntax work for?
Bill the Lizard
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
Alexander Morland
Every database has its own function for getting the current date, unfortunately.
jodonnell
+2  A: 

The SQL Server query is:

Select *
From Messages
Where MessageTime > DateAdd(dd, -1, GetDate())

As far as I can tell the (untested!) MySQL equivalent is

Select *
From Messages
Where MessageTime > ADDDATE(NOW(), INTERVAL -1 DAY)
Martynnw
A: 

There is no cross database solution, as most of them have their own date handling (and mainly interval representation) syntax and semantics, sorry.

In PostgreSQL it would be

SELECT * FROM messages WHERE messagetime >= messagetime - interval '1 day'

Vinko Vrsalovic
+1  A: 

For Sybase SQL Anywhere:

Select * From Messages Where MessageTime > dateadd( day, -1, now() )
Graeme Perrow
+1  A: 

For Oracle

SELECT * FROM messages WHERE messageTime > SYSDATE - 1

(The psuedo variable SYSDATE includes the time, so sysdate -1 will give you the last 24 hrs)

hamishmcn
A: 

If you are accessing this from an API based client (I'm guessing that is the case because of the '?'s in the query) you can do this from your program rather than through SQL.

Note: The rest is for JDBC syntax, other APIs/languages will be different syntax, but should be conceptually the same.

On the insert side do

PreparedStatement stmt = connection.prepareStatement( 
    "INSERT INTO messages " +
    "(typeId, messageTime, stationId, message) VALUES " +
    "(?, ?, ?, ?)" );
stmt.setInt(1, typeId);
stmt.setDate(2, new java.sql.Date(System.currentTimeMillis()));
stmt.setInt(3, stationId);
stmt.setString(4, message);

On the query side do:

PrepatedStatement stmt = connection.prepareStatement(
   "SELECT typeId, messageTime, stationId, message " +
   "from messages where messageTime < ?");
long yesterday = System.currentTimeMillis() - 86400000; // 86400 sec/day
stmt.setDate(1,new java.sql.Date(yesterday));

That should work in a portable manner.

John Meagher