Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the max value from two tables

Tags:

mysql

I have a query like this, to select the most recent time someone was contacted:

SELECT `user_id`, `last_contact` 
  FROM `emails_sent` 
 group by `user_id`
 order by `last_contact` desc

The above code gives a table with the last contact time for each user. Now, I have another table with contacts to users, a table with columns user_id and last_contact, among others.

How can I make my select use both tables and select the last contact time for each user from the two tables?

like image 922
luqita Avatar asked Jan 10 '12 14:01

luqita


1 Answers

Summarize the union of two summary queries, something like this.

SELECT user_id, 
       MAX(user_date) user_date
  FROM
   (
     SELECT user_id, 
            MAX(last_contact) user_date 
       FROM emails_sent
      GROUP BY user_id
   UNION ALL
     SELECT whatever_user_id_column user_id, 
            MAX(whatever_date_column) user_date 
       FROM whatever_table
      GROUP BY user_id
   )a
GROUP BY user_id
like image 161
O. Jones Avatar answered Sep 28 '22 01:09

O. Jones