Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql subquery inside a LEFT JOIN

Tags:

I have a query that needs the most recent record from a secondary table called tbl_emails_sent.

That table holds all the emails sent to clients. And most clients have several to hundreds of emails recorded. I want to pull a query that displays the most recent.

Example:

SELECT c.name, c.email, e.datesent
FROM `tbl_customers` c
LEFT JOIN `tbl_emails_sent` e ON c.customerid = e.customerid

I'm guessing a LEFT JOIN with a subquery would be used, but I don't delve into subqueries much. Am I going the right direction?

Currently the query above isn't optimized for specifying the most recent record in the table, so I need a little assistance.

like image 732
coffeemonitor Avatar asked Sep 06 '12 23:09

coffeemonitor


People also ask

Can we use subquery in left join?

Move the 'Reserve' table named in the subquery to the FROM clause and join it to 'Customers' using LEFT JOIN. The WHERE clause compares the customer_id column to the ids returned from the subquery. Hence convert the IN expression to an explicit direct comparison between id columns of two tables in the FROM clause.

Can you use a subquery with a join?

A subquery can be used with JOIN operation. In the example below, the subquery actually returns a temporary table which is handled by database server in memory. The temporary table from the subquery is given an alias so that we can refer to it in the outer select statement.

How do I join a sub query in MySQL?

A subquery is usually added within the WHERE Clause of another SQL SELECT statement. You can use the comparison operators, such as >, <, or =. The comparison operator can also be a multiple-row operator, such as IN, ANY, SOME, or ALL.


2 Answers

It should be like this, you need to have a separate query to get the maximum date (or the latest date) that the email was sent.

SELECT  a.*, b.*
FROM    tbl_customers a
            INNER JOIN tbl_emails_sent b
                ON a.customerid = b.customerid
            INNER JOIN
            (
                SELECT      customerid, MAX(datesent) maxSent
                FROM        tbl_emails_sent
                GROUP BY    customerid
            ) c ON  c.customerid = b.customerid AND
                    c.maxSent = b.datesent
like image 184
John Woo Avatar answered Sep 18 '22 15:09

John Woo


Would this not work?

SELECT t1.datesent,t1.customerid,t2.email,t2.name
FROM
(SELECT max(datesent) AS datesent,customerid
FROM `tbl_emails_sent`
) as t1
INNER JOIN `tbl_customers` as t2
ON t1.customerid=t2.customerid

Only issue you have then is what if two datesents are the same, what is the deciding factor in which one gets picked?

like image 41
mrmryb Avatar answered Sep 20 '22 15:09

mrmryb