简体   繁体   中英

How to select rows between two different columns with two different input values on same table on mysql

I have a table name as Orders. Orders table have two columns names are start_date,end_date

S.No     start_date   end_date
 1       2016-04-01   2016-04-08
 2       2016-04-28   2016-05-29
 3       2016-05-01   2016-05-39

Now I want records between start date of 2016-04-01 and end date of 2016-04-30.

Please help me on this

Assuming you want records that overlap the range:

SELECT *
  FROM orders
 WHERE start_date <= :end_range
   AND end_date   >= :start_range

In your case:

SELECT *
  FROM orders
 WHERE start_date <= '2016-04-30'
   AND end_date   >= '2016-04-01'

This works as below:

           <---RANGE-->
     <-->                                     X end_date   < :start_range
R      <---->                                 Returned
O             <---->                          Returned
W         <--------------->                   Returned
S                   <---->                    Returned
                            <-->              X start_date > :end_range

Assuming start_date is always <= end_date , you may get better results with the query below, as it gives more specificity on the start_date filter:

select * 
from Orders 
where start_date between '2016-04-01' and '2016-04-30'
    and end_date between '2016-04-01' and '2016-04-30'

您是否要:从起始日期介于'04 / 01/2016'和'04 / 30/2016'和结束日期介于'04 / 01/2016'和'04 / 30/2016'的订单中选择*

Is this what you're looking for?

select * 
from Orders 
where 
    (start_date >= '2016-04-01' and start_date < '2016-05-01'); 

Edit Update to reflect comments from OP.

SQL Fiddle

If you want only orders that ran from 4/1 - 4/30 then:

SELECT *
FROM
   orders
WHERE
   start_date = '2016-4-1'
   AND end_date = '2016-4-30'

If you want orders that either started on 4/1 OR ended on 4/30 then:

SELECT *
FROM
   orders
WHERE
   start_date = '2016-4-1'
   OR end_date = '2016-4-30'

Edit after OP comment

SELECT *
FROM
    orders
WHERE
    start_date between '2016-4-1' AND '2016-4-30'
    OR end_date between '2016-4-1' AND '2016-4-30'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM