Find data between a period in a table with start date and end date fields

0

I have a problem fetching data in a table with start date and end date fields between a period (a -filter)

The sample data is:

ID - INICIO     - FIM
1  - 01/01/2017 - 31/12/2017
2  - 10/01/2017 - 01/02/2017
3  - 01/05/2017 - 01/06/2017
4  - 15/05/2017 - 15/06/2017
5  - 01/09/2017 - 31/10/2017

I have 3 searches and expected returns

  

First search between 01/01/2017 - 12/31/2017
  expected return - 1-2-3-4-5

     

2nd search between 01/04/2017 - 06/30/2017
  expected return - 1-3-4

     

3rd Search between 02/06/2017 - 02/07/2017
  expected return - 1-4

The query I did for the first search was: link

select * from dados
where
    dt_inicio >= '2017-01-01' AND dt_inicio <= '2017-12-31'
AND dt_fim >= '2017-01-01' AND dt_fim <= '2017-12-31'
// o resultado foi ok

The query I did for the second search was: link

select * from dados
where
    dt_inicio >= '2017-04-01' AND dt_inicio <= '2017-06-30'
AND dt_fim >= '2017-04-01' AND dt_fim <= '2017-06-30'
// o resultado FALHOU

The query I did for the third search was: link

select * from dados
where
    dt_inicio >= '2017-06-02' AND dt_inicio <= '2017-07-02'
AND dt_fim >= '2017-06-02' AND dt_fim <= '2017-07-02'
// o resultado FALHOU

Follow the script to create the table and data:

CREATE TABLE IF NOT EXISTS 'dados' (
'id' int(11) NOT NULL,
  'dt_inicio' date NOT NULL DEFAULT '0000-00-00',
  'dt_fim' date NOT NULL DEFAULT '0000-00-00'
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;


INSERT INTO 'dados' ('id', 'dt_inicio', 'dt_fim') VALUES
(1, '2017-01-01', '2017-12-31'),
(2, '2017-01-10', '2017-02-01'),
(3, '2017-05-01', '2017-06-01'),
(4, '2017-05-15', '2017-06-15'),
(5, '2017-01-09', '2017-10-31')
    
asked by anonymous 08.06.2017 / 17:42

1 answer

0

After a discussion in other groups, I got a solution,

SELECT * FROM dados
WHERE 
    dt_inicio <= '$dt_fim_busca'
AND dt_fim >= '$dt_inicio_busca'

With examples passed to $dt_inicio_busca and $dt_fim_busca

$dt_inicio_busca | $dt_fim_busca
--------------------------------
01/01/2017       | 31/12/2017
01/04/2017       | 30/06/2017
02/06/2017       | 02/07/2017
    
08.06.2017 / 21:11