简体   繁体   English

LEFT JOIN里面的mysql子查询

[英]mysql subquery inside a LEFT JOIN

I have a query that needs the most recent record from a secondary table called tbl_emails_sent . 我有一个查询需要来自名为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. 我猜测使用子查询的LEFT JOIN,但我没有深入研究子查询。 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. 目前上面的查询未针对指定表中的最新记录进行优化,因此我需要一些帮助。

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

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? 如果只有两个日期是相同的,那么只有你有的问题是,选择一个的决定因素是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM