选择每个人的最后记录

时间:2016-06-23 07:12:45

标签: mysql subquery left-join

我有以下表格

tbl_investors

   id  |   first_name  |  last_name  |
---------------------------------------
   1   |      Jon      |    Cold     |
   2   |      Rob      |    Ark      |
   3   |     Rickon    |    Bolt     |

tbl_investors_ledger

  id   |   investor_id  |  amount  |
------------------------------------
  1    |        1       |   500    |
  2    |        2       |   200    |
  3    |        2       |   250    |
  4    |        2       |   300    |
  5    |        3       |   10     |
  6    |        1       |   550    |
  7    |        3       |   20     |

我只想以最新金额回报所有投资者。例如,Jon Cold与550,Rob Ark 300和Rickon Bolt 20,按姓氏字母顺序排列。

我有一个现有的查询,但它不会返回最新的投资者金额。有人可以帮助我,我做错了吗?

   SELECT t1.*, t2.*
   FROM ".tbl_investors." t1
   LEFT JOIN ".tbl_investors_ledger." t2
        ON t1.id = t2.investor_id
   LEFT JOIN (SELECT t.investor_id, max(t.id) as tid 
        FROM ".tbl_investors_ledger." t ) tt
        ON tt.investor_id = t2.investor_id AND tt.tid = t2.id
   GROUP BY t2.investor_id 
   ORDER BY t1.last_name

2 个答案:

答案 0 :(得分:2)

您可以一起使用GROUP_CONCATSUBSTRING_INDEX

SELECT I.*
    , SUBSTRING_INDEX(GROUP_CONCAT(L.amount ORDER BY L.id DESC), ',', 1) AS LastAmount
    FROM tbl_investors AS I
    LEFT JOIN tbl_investors_ledgers AS L
        ON L.investor_id = I.id
    GROUP BY I.id
    ORDER BY I.last_name

来自SQLFiddle的演示,非常感谢@zakhefron:)

答案 1 :(得分:1)

试试这个;)

 SELECT t1.*, t2.*
 FROM tbl_investors t1
 LEFT JOIN tbl_investors_ledger t2
 ON t1.id = t2.investor_id
 INNER JOIN (
     SELECT t.investor_id, max(t.id) as tid 
     FROM tbl_investors_ledger t GROUP BY t.investor_id) tt
 ON tt.investor_id = t2.investor_id AND tt.tid = t2.id
 ORDER BY t1.last_name

SQLFiddle DEMO

并查看相关的OP Retrieving the last record in each group和此博客How to select the first/least/max row per group in SQL,您可以找到更多针对您问题的解决方案。