This is a really obvious data problem, but I can't find a simple solution anywhere.
Using TYPO3 QueryBuilder, how do you select the most recent entry for each user from a table that has multiple entries per user?
uid user_id value crdate
1 1 0 123456
2 1 1 123400
3 2 1 123356
4 2 0 123300
I have tried loads of raw SQL approaches and eventually found a method that works, based on this solution - How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
SELECT *
FROM `tx_tablename` AS `tt`
INNER JOIN (
SELECT `uid`, `user_id`, MAX(`crdate`) AS `MaxDateTime`
FROM `tx_tablename`
GROUP BY `user_id`
) AS `groupedtt`
ON `tt`.`user_id` = `groupedtt`.`user_id`
AND `tt`.`crdate` = `groupedtt`.`MaxDateTime`
WHERE `tt`.`consent_content` = 3
But I can't see how to reproduce this in QueryBuilder, as the ->join() statement will only accept table names as parameters, not SQL, and ->join() will only accept one joining condition, not two.
Has anyone else found a solution that works in QueryBuilder? Many thanks
The quoting is done in the TYPO3 QueryBuilder. You can bypass it by using the ConcreteQueryBuilder directly.
But doing this, you have to quote identifier yourself, or exceptions would be thrown.
This should do the trick in your pseudo code:
edit 1
Fixed code example. Need
quoteIdentifier()
instead ofcreateNamedParam()
.Note
If you use nested selects/subselects AND using named parameters, you have to use the outermost queryBuilder instance for named parameter creation, not the current level queryBuilder.