W
W
w_b_x2017-06-22 23:34:50
PHP
w_b_x, 2017-06-22 23:34:50

How to cross-group output via GROUP BY in MYSQL?

Hello!
There is a request like:

SELECT `from_user`,`to_user`,`text`,`read_state` FROM 
( SELECT `from_user`,`to_user`,`text`,`read_state`,`ts` FROM `gr_messages`  WHERE `to_user` = '1' OR `from_user` = '1' ORDER BY `ts` DESC ) 
as inv GROUP BY `from_user` ORDER BY `ts` DESC LIMIT 10

The DB looks like this
1ba09f448a474a68ab64e1042ce0911d.png
:
.
The query result is
96f3cc81aa5d4e6fb1e15be7bb2f75a1.png
:
.
But it is also necessary to combine these two results, and in favor of `from_user`, it should contain 3, and the `text` column from the line with the largest ts, i.e. one line should be obtained as a result of this kind (made a screen through editing html):
1595fd1573fe4966995457643cc58ac8.png
.
How to do this, how to fix the request? save

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Tratorov, 2017-06-23
@w_b_x

You want the impossible. I think that you have a problem in the algorithm or logic, that's why the problem arose. Think again.
As for your query, this grouping will no longer work on MySQL 5.7 due to the stricter sql_mode rules.
There is no way for you to get the line that you drew, because text = Good) wrote not 3, but 1.
But if you really want to, then shift the desired grouping to the application, calculating who 1 was talking to. Get away from the database - save your time and DBMS resources.
Or, I already said - change the logic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question