4

I'm using MySql 5.5.

I need to find a userid on a date with a particular ip address.

The fields are userid, ipaddress, startdate, enddate.

So for instance I am looking for a userid with ip address 192.168.1.1 on Sep 12 2011.

the query would be similar select * from database where ipaddress='192.168.1.1' and 2011-12-09 is in(startdate and enddate);

Any help to pointing out this logic flaw is welcome. Thank you.

notmyname
  • 69
  • 2
  • 6

3 Answers3

4

It's not very clear if you want:

'2011-12-09' BETWEEN startdate AND enddate

or:

'2011-12-09' = startdate AND '2011-12-09' = enddate
ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235
  • note that `between` does a `<=`/`>=`-comparision, so doing `=` on start- and enddate might not give the exact same result in every case. – oezi Feb 01 '12 at 15:08
  • Apologies, I want the first one ''2011-12-09' BETWEEN startdate AND enddate' – notmyname Feb 01 '12 at 15:20
1

the obvious solution would be like:

  [...]
AND
  startdate <= '2011-12-09'
AND
  enddate >= '2011-12-09'

but theres a shortcut using BETWEEN so you can simply write:

  [...]
AND
  '2011-12-09' BETWEEN startdate AND enddate

note: BETWEEN also works for numbers, strings and other stuff, and it's possible to negate it by writing NOT BETWEEN - quite useful sometimes.

oezi
  • 51,017
  • 10
  • 98
  • 115
  • thanks for the hint, ypercube - i'm not a native english speaker and so this is what happens if you're too lazy to look up a word... but now it's correct. – oezi Feb 01 '12 at 15:06
0

Since there is a start and end date, maybe something along the line of:

SELECT * FROM table WHERE ipaddress = '192.168.1.1' AND '2011-12-09' >= startdate AND '2001-12-09' <= enddate;

Or as pointed out by ypercube you can use BETWEEN:

SELECT * FROM table WHERE ipaddress = '192.168.1.1' AND '2011-12-09' BETWEEN startdate AND enddate;
mauris
  • 42,982
  • 15
  • 99
  • 131
  • formatting the querys would make this much easier to read, having to scroll horizontally is annoying ;) – oezi Feb 01 '12 at 14:59