MySQL -連接相關表的最后一行

[英]MySQL - Join last row of related table


I have a problem that I have searched for and can't find answers that offer any help.

我有一個問題,我一直在尋找,卻找不到任何能提供幫助的答案。

There are 3 tables: orders, customers, and teams. Each order has a customer and a team. My problem is that for each customer, I am trying to get their total orders, and then the team that was assigned to their last order.

有3個表:訂單、客戶和團隊。每個訂單都有一個客戶和一個團隊。我的問題是,對於每個客戶,我都試圖獲得他們的總訂單,然后是分配給他們最后一個訂單的團隊。

My query so far (works fine):

到目前為止我的查詢(工作正常):

SELECT c.id, MAX(o.timestamp) AS "Last Order", COUNT(o.id) AS "Total Orders", SUM(o.price) AS "Total Spend"
FROM orders o
LEFT JOIN customers c ON o.customer = c.id
WHERE o.timestamp > '2012-01-01 00:00:00'
GROUP BY c.id
ORDER BY c.id

I can't figure out how to join the team.name for the last order they placed, without affecting the rest of the query that I have.

我不知道如何加入他們最后下的訂單的team.name,而不會影響我的查詢的其余部分。

Sample Tables and Desired Result:

樣例表和期望結果:

Customers:

客戶:

╔════╦═════════════╗
║ ID ║    NAME     ║
╠════╬═════════════╣
║  1 ║ John Smith  ║
║  2 ║ Jim Jimmers ║
╚════╩═════════════╝

Teams:

團隊:

╔════╦═════════════╗
║ ID ║    NAME     ║
╠════╬═════════════╣
║  1 ║ Red         ║
║  2 ║ Blue        ║
╚════╩═════════════╝

Orders:

訂單:

╔═══════╦═════════════════════╦══════════╦══════╦═══════╗
║  ID   ║       TIMESTAMP     ║ CUSTOMER ║ TEAM ║ VALUE ║
╠═══════╬═════════════════════╬══════════╬══════╬═══════╣
║ 34656 ║ 2012-03-04 14:23:44 ║        1 ║    2 ║    20 ║
║ 37345 ║ 2012-04-12 11:32:07 ║        2 ║    2 ║    25 ║
║ 38220 ║ 2012-07-18 09:53:54 ║        1 ║    2 ║    15 ║
║ 39496 ║ 2012-07-03 10:11:32 ║        1 ║    1 ║    38 ║
║ 41752 ║ 2012-09-17 19:34:05 ║        1 ║    2 ║     9 ║
║ 43734 ║ 2012-11-23 07:52:12 ║        2 ║    1 ║    20 ║
╚═══════╩═════════════════════╩══════════╩══════╩═══════╝

How do I select a result like:

如何選擇如下結果:

╔════╦═════════════╦═════════════════════╦═══════════╦══════════════╦═════════════╗
║ ID ║    NAME     ║      LAST_ORDER     ║ TEAM_NAME ║ TOTAL_ORDERS ║ TOTAL_SPEND ║
╠════╬═════════════╬═════════════════════╬═══════════╬══════════════╬═════════════╣
║  1 ║ John Smith  ║ 2012-09-17 19:34:05 ║ Blue      ║           4  ║          82 ║
║  2 ║ Jim Jimmers ║ 2012-11-23 07:52:12 ║ Red       ║           2  ║          45 ║
╚════╩═════════════╩═════════════════════╩═══════════╩══════════════╩═════════════╝

3 个解决方案

#1


2  

You can use a query similar to this:

您可以使用類似以下的查詢:

select c.id,
  c.name,
  o1.Last_Order,
  t.name Team_Name,
  o3.Total_Orders,
  o3.Total_Spend
from customers c
inner join
(
  select max(timestamp) Last_Order,
    max(id) Last_id,
    customer
  from orders
  WHERE timestamp > '2012-01-01 00:00:00'
  group by customer
) o1
  on c.id = o1.customer
inner join orders o2
  on c.id = o2.customer
  and o1.Last_Order = o2.timestamp
  and o1.Last_id = o2.id
inner join teams t
  on o2.team = t.id
inner join
(
  select count(team) Total_Orders,
    sum(value) Total_Spend,
    customer
  from orders 
  WHERE timestamp > '2012-01-01 00:00:00'
  group by customer
) o3
  on c.id = o3.customer
WHERE o2.timestamp > '2012-01-01 00:00:00'

See SQL Fiddle with Demo

參見SQL小提琴演示

#2


1  

I like to do this using a group_concat trick:

我喜歡使用group_concat技巧:

SELECT c.id, MAX(o.timestamp) AS "Last, Order", COUNT(o.id) AS "Total Orders",
       SUM(o.price) AS "Total Spend",
       substring_index(group_concat(teamname order by o.timestamp desc), ',', 1) as LastTeam
FROM orders o left outer join
     customers c ON o.customer = c.id left outer join
     teams t
     on o.teamid = t.id
WHERE o.timestamp > '2012-01-01 00:00:00'
GROUP BY c.id
ORDER BY c.id

#3


0  

Give this a try,

給這一個嘗試,

SELECT  a.ID, 
        a.Name Customer_Name,
        c.TimeStamp Last_ORDER,
        c.Name AS Team_Name,
        COUNT(b.Customer) AS Total_Order,
        SUM(b.Value) AS Total_Spend
FROM    Customers a
        INNER JOIN Orders b
            ON a.ID = b.Customer
        INNER JOIN
        (
            SELECT  o.Customer, 
                    o.TimeStamp,
                    q.Name
            FROM    Orders o
                    INNER JOIN
                    (
                        SELECT  Customer, MAX(ID) max_ID
                        FROM    Orders
                        GROUP   BY Customer
                    ) p ON o.Customer = p.Customer AND
                            o.ID = p.max_ID
                    INNER JOIN Team q
                        ON o.Team = q.ID
        ) c ON a.ID = c.Customer
GROUP   BY a.ID, a.Name

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/03/04/7302c736aa49aed593c2bbbd5e54749c.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com