Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Select in Select

I need to execute that SQL query:

SELECT * FROM (SELECT * FROM Messages WHERE author = :userId: OR target = :userId: ORDER BY timestamp DESC) as one_base GROUP BY author, target ORDER BY timestamp DESC LIMIT 12

But as a result i get only it:

Syntax error, unexpected token (, near to 'SELECT * FROM Messages WHERE author = :userId: OR target = :userId: ORDER BY timestamp DESC) as one_base GROUP BY author, target ORDER BY timestamp DESC LIMIT 12', when parsing: SELECT * FROM (SELECT * FROM Messages WHERE author = :userId: OR target = :userId: ORDER BY timestamp DESC) as one_base GROUP BY author, target ORDER BY timestamp DESC LIMIT 12 (176)

It would be better to somehow transform query so that it fits into the framework PHQL, to attempt it with pure SQL.


Explanation of the need for such query on the Russian: Первый (вложеный) запрос выбирает все сообщения между текущим пользователем и другими возможными собеседниками, сортируя их по убыванию времени, чтобы наверху были только самые новое сообщения. Вторым запросом я группирую эти сообщения по паре "autho-target" и опять же сортирую по убыванию времени написания. Таким образом получается по 2 сообщения на диалог: "я-ты" и "ты-я", которые за тем уже в цикле приводятся к виду только с самым последним сообщением.



84.5k
Accepted
answer

PHQL does not support subqueries, you can use a raw query there: http://docs.phalconphp.com/en/latest/reference/phql.html#using-raw-sql