简体   繁体   中英

SQL - Using query with date parameters with IN used for a sub-query

I have the following query which is returning nothing:

SELECT e.`value`, e.`machine_id`, e.`date_recorded` 
from engine_hours e 
where e.`date_recorded` >= NOW() - INTERVAL 32 DAY 
  AND e.`date_recorded` <= NOW() - INTERVAL 2 DAY 
  AND e.`machine_id` IN (SELECT m.id FROM  `machines` m WHERE m.`title` =  'ABC-123')

When I break the query and sub-query into two independent queries they work fine

Question: How can I use what the sub-query returns to the main query, alongside the date boundaries in the WHERE section of the main query.


Clarification & Better Explanation: I get no errors.

When I run the sub-query as a query of its own ie:

SELECT m.id FROM  `machines` m WHERE m.`title` =  'ABC-123'

it returns 1234 which is correct. And when I use this returned value 1234 in the main query ie:

SELECT e.`value`, e.`machine_id`, e.`date_recorded` 
from engine_hours e 
where e.`date_recorded` >= NOW() - INTERVAL 32 DAY 
  AND e.`date_recorded` <= NOW() - INTERVAL 2 DAY 
  AND e.`machine_id = '1234'

I get the data I am after. I can't seem to understand what I am doing wrong.


Explaining the dates:

I want to get the data starting from 32 days ago till 2 days ago:

where e.`date_recorded` >= NOW() - INTERVAL 32 DAY 
AND e.`date_recorded` <= NOW() - INTERVAL 2 DAY 

ie now is 2019-03-06, 32 days ago ( NOW() - INTERVAL 32 DAY ) will be 2019-02-02 and similarly 2 days ago will be 2019-03-04 .

The information I want should be greater than or equal to ( >= ) 2019-02-02 and less then or equal to ( <= ) 2019-03-04 .

Use join

SELECT e.`value`, e.`machine_id`, e.`date_recorded`,m.id
from engine_hours e join `machines` m on e.`machine_id`=m.id
where e.`date_recorded` >= NOW() - INTERVAL 32 DAY 
  AND e.`date_recorded` <= NOW() - INTERVAL 2 DAY 
  and m.`title` =  'ABC-123'

EDITED

I've just tried it myself, it's working fine. Each query individually is correct (syntax & logic). Both queries together is also correct (syntax & logic).

So it's either:

  • The machine_id in the targeted rows in engine_hours is different than 1234 .
  • The date_recorded in the targeted rows in engine_hours is not of the date range desired.
  • The query you posted in StackOverflow is slightly different than the one you have in your source code.
  • Maybe you're including the database name in the query. If so, make sure you're targeting the correct database name.

I suggest you delete the entire query in your source code and re-write it again. You probably have some hidden character(s), wrong operator used, or alike.

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