Related question: MySQL "Group By" and "Order By"
I can use the following query to retrieve a list of downloads for an item:
SELECT items.id, items.name, users.fullName AS downloadedBy, dl.dateTime AS lastDownload
FROM items
LEFT OUTER JOIN downloads dl ON dl.itemID = items.id
LEFT JOIN users ON users.id = dl.userID
WHERE items.id = '47'
ORDER BY dl.dateTime DESC
This, as expected, returns a list of downloads with the latest at the top.
What I want to do is retrieve the last download and the total number of downloads for the item.
This query:
SELECT items.id, items.name, users.fullName AS downloadedBy, dl.dateTime AS lastDownload, COUNT(dl.id) AS total
FROM items
LEFT OUTER JOIN downloads dl ON dl.itemID = items.id
LEFT JOIN users ON users.id = dl.userID
WHERE items.id = '47'
ORDER BY dl.dateTime DESC
GROUP BY items.id
returns the correct total, but the download details (user name and date) is a random entry from the middle of the list. Wrapping the main query in a subquery and putting the GROUP BY afterwards, as described in the linked question, has the same effect. Is it possible to retrieve both the last download and the total in one query?
I'm using MySQL version 5.7.21 with ONLY_FULL_GROUP_BY
disabled.
[EDIT] To answer Ankit's comment:
Output from first query:
id | name | downloadedBy | lastDownload ============================================== 47 | Item 47 | Matilda | 2018-08-18 19:10 47 | Item 47 | Marmaduke | 2018-08-14 07:21 47 | Item 47 | Simon | 2018-06-11 14:02 47 | Item 47 | Boris | 2018-06-11 14:00
Desired output:
id | name | downloadedBy | lastDownload | total ====================================================== 47 | Item 47 | Matilda | 2018-08-18 19:10 | 4
Actual output from second query:
id | name | downloadedBy | lastDownload | total ====================================================== 47 | Item 47 | Simon | 2018-06-11 14:02 | 4