1

TABLE 1

---------------------------------------
| id | item | MU | quantity | file_id |
---------------------------------------
| 1  |item1 | oz | 3.5      | 003     |
| 2  |item2 | kg | 1.1      | 001     |
| 3  |item1 | oz | 0.2      | 001     |
| 3  |item1 | kg | 3        | 001     |

TABLE 2

 ----------------------------
 | id | date      | file_id |
 ----------------------------
 | 1  |timestamp1 | 001 |
 | 2  |timestamp2 | 002     |
 | 3  |timestamp3 | 003     |

What i'm trying to do is to select the sum of quantity for each group of items that have the same MU. I manage to do that with this query.

$query = "SELECT item,SUM(quantity) from table1 GROUP BY item,mu";

with a great result, exactly what i wanted
----------------------------------
| id | item | MU | SUM(quantity) |
----------------------------------
| 1  |item1 | oz | 3.7           |
| 2  |item2 | kg | 1.1           |
| 3  |item1 | kg | 3             |

But now, how do i get only the rows that their file_id date is BETWEEN two timestamps ?

1
  • What's the PRIMARY KEY on each of these tables? Commented May 19, 2013 at 10:09

2 Answers 2

3

You can join both table using INNER JOIN. The result of the query will only show items from Table1 which matches between the two dates, otherwise it is not included in the result list.

SELECT  MIN(a.iD) ID, a.item, a.MU,
        SUM(a.quantity) totalQuantity
FROM    table1 a
        INNER JOIN table2 b
            ON a.file_ID = b.file_ID 
WHERE   b.date BETWEEN startDateHere AND endDateHere 
GROUP   BY a.item, a.MU

To further gain more knowledge about joins, kindly visit the link below:

Sign up to request clarification or add additional context in comments.

2 Comments

i think you want this. Use INNER JOIN.
one more thing, MIN(a.iD) ID is optional.
2

You can manage to achieve this using LEFT JOIN and joining the two tables in a single query, simply replace initialdate and finaldate with your current timestamp

$query = "SELECT a.id, a.item, a.mu, SUM(a.quantity) as total_quantity from table1 a left join table2 b ON a.file_id = b.file_id WHERE b.date BETWEEN initialdate AND finaldate GROUP BY a.item,a.mu";

4 Comments

great, i knew that i should read more about mysql JOIN :D, it's not very clear in my head :) , thanks
so if i want from all these returned by your query just those items (from table 1) that their id is present in a third table?
@user348078 i would suggest to post a new question with your code and the problem you find in compiling it
there is no need to post a new question. the simpliest answer with the followup question by the OP is to use INNER JOIN not LEFT JOIN. just as simple as that.

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.