MySQL: Order by max date of a joined table [duplicate] - mysql

This question already has answers here:
Ordering a MySQL result set by a MAX() value of another table
(2 answers)
Closed 4 years ago.
I have two tables - groups and messages.
Messages has the following fields group_id and date_created. So a lot of messages can be added to a single group. I want to select all groups from table - most relevant on top, i.e. order by latest message date. I've tried something like this
SELECT g.*, MAX(m.date_created) AS mdt FROM groups g
LEFT JOIN messages m ON g.id = m.group_id
ORDER BY mdt DESC;
But this query returns only one row and max message date from the whole table.

You are missing group by:
SELECT g.*, MAX(m.date_created) AS mdt
FROM groups g LEFT JOIN
messages m
ON g.id = m.group_id
GROUP BY g.id
ORDER BY mdt DESC;

Related

How to get latest messages for each user in mysql? [duplicate]

This question already has answers here:
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 2 years ago.
I have database to store customer and messages
I am trying to get list of all the customer and their latest messages like first screen in messenger.
SELECT *
FROM message AS m
LEFT JOIN customer AS c ON c.id=m.sender_id
ORDER BY m.sent_at DESC
but this returns all the message for all user. I've also tried doing this
SELECT *
FROM message AS m
LEFT JOIN customer AS c ON c.id=m.sender_id
GROUP BY c.id
but this doesn't run on all databases and cannot sort result set to get latest messages only.
One option uses row_number(), available in MySQL 8.0:
select * -- better enumerate the columns you want here
from customer as c
left join (
select m.*, row_number() over(partition by m.sender_id order by sent_at desc) rn
from messages m
) m on on c.id = m.sender_id and m.rn = 1
order by m.sent_at desc
This gives you the last message per customer. You can change the condition on rn if you want more messages (rn <= 3 would give you three messages per customer).
Note that I changed the order of the tables in the left join, so it allows customers without messages (rather than messages without customers, which probably does not make sense).
If you are running an earlier version, than an alternative is to filter with a subquery:
select * -- better enumerate the columns you want here
from customer as c
left join messages m
on m.sender_id = c.id
and sent_at = (select min(m1.sent_at) from messages m1 where m1.sender_id = m.sender_id)
For perforamnce with the correlated subquery, consider an index on (sender_id, sent_at) (ideally, there should be no duplicates in these columns).

How to remove duplicate results? [duplicate]

This question already has answers here:
Retrieving the last record in each group - MySQL
(33 answers)
Closed 3 years ago.
I'm coding a message system using mysql.
Everything works fine when I list users whom I'm conversing with, until I want to add date of the last or the start of conversation.
When I add a.date I get duplicate results when the date isnt the same.
Here is my sqlfiddle
Since, you were pulling only user_id then in both cases (send/recieve) it was giving you distinct record. But now with date it is no more distinct. you need to do something like:
SELECT temp.id_user, MAX(temp.date) as date
FROM
(
SELECT users.id_user,
a.date
FROM users
LEFT JOIN message AS a
ON users.id_user = a.id_user_recipient
LEFT JOIN message AS b
ON a.id_user_recipient = b.id_user_sender
WHERE a.id_user_sender = 1
UNION DISTINCT
SELECT users.id_user,
a.date
FROM users
LEFT JOIN message AS a
ON users.id_user = a.id_user_sender
LEFT JOIN message AS b
ON a.id_user_sender = b.id_user_recipient
WHERE a.id_user_recipient = 1
) as temp
GROUP BY temp.id_user;
Grabbing max(date) will ensure to return only one record as with group by

computed column to use further in mysql query [duplicate]

This question already has answers here:
Can I reuse a calculated field in a SELECT query?
(7 answers)
Closed 3 years ago.
I want to know how can i use two columns already computed in sql query to get one more result from their values.
my query is
SELECT s.date date
, p.id
, SUM(COALESCE(p.avgcost,0)) costofsale
, SUM( COALESCE(s.actual_payable, 0 ) ) total_sales
, (total_sales - costofsale) tots
FROM sales s
LEFT
JOIN sale_items si
on si.sale_id = s.id
LEFT
JOIN products p
on p.id = si.product_id
WHERE DATE(s.date) = DATE('2019-09-10 14:48:50')
I want to get the result from total_sales - costofsale that is already computed in query.
I don't want to alter or update my table.
I just need to use those two columns to give me the result by calculating them.
I have not found any solution over google.
MySQL 8 includes WITH statements which allows for creating calculated values without using variables.
WITH statement VS subquery

MySql sort on join? [duplicate]

This question already has answers here:
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 6 years ago.
I have two tables jobs, notes.
I want to output a list of jobs that are of status='lost' along with the most recent note for that job (based on the date the note was created).
Here's my query:
select jobs.id, jobs.name, jobs.status
inner join notes on jobs.id=notes.jobId
where jobs.status='lost'
group by jobs.id
order by notes.createDate DESC
I would have thought that the output would show the most recent note for a given job. But it shows the first note for that job. I have changed sort from DESC to ASC just to see what happens...and the output is the same.
Then I tried to nest a select from notes inside the main select..and it hung.
This should be easy and I am sure it is..what am I missing ?
There is many options to solve this, but you may use a sub query.
select jobs.id, jobs.name, jobs.status
(select noteField from notes on jobs.id=notes.jobId order by createDate desc limit 1) note
where jobs.status='lost'
When I'm in a similar boat, I've resorted to using a subquery on the join:
select jobs.id, jobs.name, jobs.status
from jobs
inner join notes on jobs.id = notes.jobId
and notes.createDate = (select max(notes.createDate)
from notes
where jobs.id = notes.createDate
group by notes.jobId)
where jobs.status='lost'
group by jobs.id
order by notes.createDate DESC

Single query to get the messages and count their answers

I have a mysql DB with two tables:
messages
message_answers
I'd like to fetch all messages and the number of answers for each of them, like:
first message (10 answers)
second message (5 answers)
Is it possible with a single sql query ?
I tried a query and a subquery for the count, but I don't know how to have the current id from the main query to make the "WHERE" restriction on the subquery (like: "message_answers.message_id = messages.id").
Thank you,
Sébastien
SELECT m.message, COUNT(ma.answer_id) AS AnswerCount
FROM messages m
LEFT JOIN message_answers ma
ON m.id = ma.message_id
GROUP BY m.message
select m.id, count(ma.id)
from messages m
join join message_answer ma on ma.id = m.message_id
group by 1