简体   繁体   中英

MySQL select between two dates not working as expected

I'm trying to create a query that will select all dates between two dates
This is my query:

$query = "SELECT DISTINCT * FROM D1,D2
    WHERE D1.DATE_ADDED BETWEEN '$date1' AND '$date2' AND D1.D1_ID = D2.D2_ID";

The trouble is, it is not returning anything, but not producing an error either

So I tried inputting it directly into phpMyAdmin like this

SELECT DISTINCT * FROM D1,D2
    WHERE D1.DATE_ADDED BETWEEN '2011-01-01' AND '2011-12-12'
        AND D1.D1_ID = D2.D2_ID`

then like this

SELECT DISTINCT * FROM D1,D2
    WHERE D1.DATE_ADDED BETWEEN '2011-01-01' AND '2011-12-12'

and like this

SELECT * FROM D1
    WHERE DATE_ADDED BETWEEN '2011-01-01' AND '2011-12-12'

and I just get

MySQL returned an empty result set (ie zero rows). ( Query took 0.0003 sec )

Yes, my tables exist, and so do the columns:)

In the first cases the lack of results could be because of the inner join. For a result to be in the set it would require a record in both tables, ie. a record from d1 would not appear unless d2 also had that id in the d2_id column. To resolve this, if that is correct for your business logic, use left join .

However, the last of your cases (without the join) suggests the reasons is a lack of matching records in the first (left) table d1.

Without the full dataset we can't really comment further, since all the code you are running is perfectly valid.

If you always want to select an entire year it is easer to select it like this:

SELECT * FROM D1 WHERE YEAR(DATE_ADDED) = 2011;

Please implement below code

SELECT DISTINCT * FROM D1,D2
    WHERE D1.DATE_ADDED BETWEEN DATE_FORMAT('2011-01-01','%Y-%m-%d')
        AND DATE_FORMAT('2011-12-12','%Y-%m-%d')
        AND D1.D1_ID = D2.D2_ID`

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