adam
adam

Reputation: 405

Select before specific date from one day only

I need to retrieve data from MySQL from one day, but I don't know the interval between two rows (there may be 4 rows from one day and a gap of a week for example).

Let's say I have: (following isn't code)

3 rows where date = 2015-06-15
1 row where date = 2015-06-09
4 rows where date = 2015-06-05

I want to retrieve all 4 rows from 2015-06-05 with

[...] WHERE `date` < '2015-06-07'

or only one row from 2015-06-09 with

[...] WHERE `date` < '2015-06-14'

Is that possible with SQL only?

Upvotes: 0

Views: 796

Answers (3)

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35780

I think you want something like this:

select * from table
where date  = (select max(date) from table where date < '2015-06-14')

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269563

If I understand correctly, you want to receive one days worth of rows before a given date. I think that would be:

SELECT t.*
FROM table t
WHERE date = (SELECT MAX(t2.date) FROM table t2 WHERE t2.`date` < '2015-06-07')

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Yes. You can do like this:

(SELECT * FROM `table` WHERE DATE(`date`) = '2015-06-15' LIMIT 0, 3)
UNION
(SELECT * FROM `table` WHERE DATE(`date`) = '2015-06-09' LIMIT 0, 1)
UNION
(SELECT * FROM `table` WHERE DATE(`date`) = '2015-06-09' LIMIT 0, 4)
UNION
SELECT * FROM `table` WHERE DATE(`date`) < '2015-06-07'
UNION
(SELECT * FROM `table` WHERE DATE(`date`) < '2015-06-14' LIMIT 0, 1)

Upvotes: 0

Related Questions