Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY different column conditionally

Tags:

sql

mysql

I want to show a list of chat messages.

For this I have a SELECT statement:

SELECT id, `from`, sent, message, recd FROM chat 
WHERE id IN(
  SELECT MAX(id) FROM chat
  WHERE `to` = ? GROUP BY `from`
)
ORDER BY id DESC

The problem is, I want to select messages that to = maria and from = maria conditionally.

That is, if to = maria I want to group by from, and if from = maria, I want to group by to.

How can I change this GROUP BY dynamically?

like image 362
RGS Avatar asked Aug 03 '26 21:08

RGS


1 Answers

I would got for a UNION.

(SELECT id, 'from' as direction, m_from AS fromto, sent, message, recd
FROM chat WHERE id IN (SELECT MAX(id) FROM chat WHERE to = 'Maria' GROUP BY m_from))
UNION
(SELECT id, 'to' as direction, m_to AS fromto, sent, message, recd FROM chat
WHERE id IN (SELECT MAX(id) FROM chat WHERE m_from = 'Maria' GROUP BY to))

If you select MAX(id) an ORDER BY id statement is not necessary.

You can add extra fields in the SELECT clause as I did with 'direction'.

like image 128
flowit Avatar answered Aug 06 '26 11:08

flowit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!