I have a table with a list of consignments for different users (table name is consignments). This table contains the consignment id (cons_id) as PK, the user_id and the date (and other details).
I have another table which contains the details of these consignments (table name is consignment). It has item_id as PK, cons_id as FK, the weight, tracking numbers and other details of the consignment. There are more than one entry in this table with the same foreign key which relates to a single entry in the first table (consignments).
I want to select all the entries in the first table (consignments) for a specific user, together with details obtained from the 2nd table (i.e. the total weight of all the items for a specific consignment, which are entries in the 2nd table, etc.).
I use the following mysql command:
SELECT a.cons_id, a.user_id, a.date,
sum(c.weight) AS weight, sum(c.weight*2) AS amount,
count(c.tracking) AS qty
FROM `consignments` AS a LEFT JOIN `consignment` AS c
ON c.cons_id = a.cons_id WHERE a.user_id = 103
This returns only the first item in the consignments table for that specific user and not the remainder of the entries. Off course, if I do not join it with the 2nd table, all the entries are returned.
I am not sure whether the aggregates like sum is the problem and how to do it correctly.
Any suggestion would be highly appreciated.
Use group by:
Example doing the weight (more sum() terms can be easily added):
Proof:
Run the above query