2

I am executing a query that obviously contains a subquery in MySQL.

Let me just jump into the code:

SELECT DATEDIFF(CURDATE(), 
(SELECT due FROM checkOut JOIN People ON checkOut.p_id = People.p_id
 WHERE CASE WHEN DATE_SUB(date_add(CURDATE(),INTERVAL 4 MONTH), INTERVAL 3 MONTH) 
 >= checkOut.checkTime THEN 1 ELSE 0 END ORDER BY checkOut.due)
 );

The main query is the SELECT DATEDIFF(). Within that is my subquery which essentially searches through the table to look for items that are overdue based on an interval. I know that there will be multiple rows returned from the query and that it will not work with how I currently have it set up.

What I want are multiple values to be returned from my SELECT DATEDIFF(), so that I can loop through it with php later. To elaborate, I want each of the rows returned in the subquery to have an associated value from DATEDIFF(). How can I modify this query to do what I want? Or if anyone has a better method, please let me know.

Any help is appreciated.

In case you are wondering the why there is a DATE_ADD() within the DATE_SUB(), it is to simply make the query work for today.

2 Answers 2

3

get rid of the subquery, you can calculate the difference directly.

SELECT  DATEDIFF(CURDATE(), due), due 
FROM    checkOut JOIN People 
            ON checkOut.p_id = People.p_id
WHERE   CASE 
           WHEN DATE_SUB(date_add(CURDATE(),INTERVAL 4 MONTH), INTERVAL 3 MONTH) 
                    >= checkOut.checkTime 
           THEN 1 
           ELSE 0 
        END 
ORDER BY checkOut.due
Sign up to request clarification or add additional context in comments.

2 Comments

That's interesting. Out of curiosity, is there a performance difference between using subqueries or not? It works great by the way.
That's what I was looking for (y)
0

Use the subquery as table. e.g. below:

SELECT DATEDIFF(CURDATE(), d.due)
FROM 
 (SELECT due FROM checkOut JOIN People ON checkOut.p_id = People.p_id
  WHERE CASE WHEN DATE_SUB(date_add(CURDATE(),INTERVAL 4 MONTH), INTERVAL 3 MONTH) 
       >= checkOut.checkTime THEN 1 ELSE 0 END ORDER BY checkOut.due) 
  ) AS d;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.