MYSQL左连接多个表但只选择最近的行

时间:2018-04-03 08:58:20

标签: mysql sql left-join

我有三个表(form_completions,customer_sessions和conversion_sessions),它们的设计如下所示,为了这个例子的目的,它们是严重条纹的:

Form_completions:

id  | name | email
------------------------
101 | Tom  | tom@website.com
102 | Ben  | ben@website.com

Customer_sessions:

id | customer_id | session_id | session_source
---------------------------------
1  | 900         | 9kc73bsf   | twitter
2  | 901         | 15jvuw83   | google
3  | 901         | 45h73bgf   | twitter

Conversion_sessions:

id | customer_id | session_id | form_completion_id
------------------------------------
1  | 900         | 9kc73bsf   | 101
2  | 901         | 45h73bgf   | 102

我目前拥有的查询是:

SELECT  custsess.session_source,
        c.id as form_conversion_id,
        c.name,

FROM    conversion_sessions convsess

LEFT JOIN   form_completions fc
ON          convsess.`form_completion_id` = fc.`id`

LEFT JOIN   customer_sessions custsess
ON          custsess.`customer_id` = convsess.`customer_id`

这将给我以下内容:

session_source | form_conversion_id | name
------------------------------------------
twitter        | 101                | Tom
google         | 102                | Ben
twitter        | 102                | Ben 

但我需要的是避免重复form_conversion_id,只包含最新版本,所以它会...

session_source | form_conversion_id | name
------------------------------------------
twitter        | 101                | Tom
twitter        | 102                | Ben 

希望这是有道理的。

3 个答案:

答案 0 :(得分:1)

解决您的问题:

SELECT  custsess.session_source,
        fc.id as form_conversion_id,
        fc.name
FROM    conversion_sessions AS convsess
INNER JOIN   form_completions AS fc
ON convsess.form_completion_id = fc.id
INNER JOIN   customer_sessions AS custsess
ON          custsess.customer_id = convsess.customer_id
AND         custsess.session_id  = convsess.session_id

加入时,您忘记加入customer_sessionscoversion_sessions加入session_id

<强>输出:

session_source  form_conversion_id  name
twitter                01           Tom
twitter                 102         Ben

如需演示,请点击以下链接:

  

https://www.db-fiddle.com/f/pQG4VCWAnoGtRJa6MkvST6/0

答案 1 :(得分:0)

查看您的数据您应该只使用内部联接

您应该在子查询上使用内部联接来获取max session_id

SELECT  custsess.session_source,
        c.id as form_conversion_id,
        c.name,

FROM    conversion_sessions convsess
customer_sessions custsess ON custsess.`customer_id` = convsess.`customer_id`
INNER JOIN  (
  select customer_id, max(session_id) as  max_sess
  from Customer_sessions
  group by customer_id
) t on t.customer_id = custsess.customer_id and t.max_sess = custsess.session_id

INNER JOIN   form_completions fc ON   convsess.`form_completion_id` = fc.`id`

答案 2 :(得分:0)

您需要一个子查询来获取最新信息,将您的JOIN更改为此类

        LEFT JOIN   customer_sessions custsess
        ON custsess.id =
        (
           SELECT MAX(id) 
           FROM Customer_sessions
           WHERE c.id = custsess.customer_id 
        )