MYSQL-从两个表连接并显示一列的不同数据

时间:2017-05-01 09:24:37

标签: mysql sql join

我在下面定义了两个表personInfo和personPayment。

表personInfo =>

 personId  |     personName
    1      |         personA
    2      |         personB

表personPayment =>

   paymentId   |    personId  |     paymentPending
    1          |         1         |         500
    2          |         2         |         700
    3          |         1         |         350

我想要的是将 personName 加入 personPayment 中每个personId的最后一条记录。这意味着我想得到如下所示的结果:

personName  |     paymentPending
personA     |         350
personB     |         700

我写的查询是:

 SELECT a.paymentPending, b.personName FROM personPayment a, personInfo b

 WHERE a.personId  = b.personId GROUP BY a.personId ORDER BY a.paymentId DESC

它正在向我返还第一个待付人。但我想得到每个人的最后一笔待付款。我该怎么办?需要帮助!

2 个答案:

答案 0 :(得分:3)

试试这个: -

SELECT a.personName,b.paymentPending FROM 
    personInfo a
    inner join
    (
    SELECT a.personid, a.paymentPending from
    personPayment a
    inner join
      (
      SELECT personId, max(paymentid) as maxid 
      FROM personPayment 
      GROUP BY personId
      ) b
    on a.paymentid=b.maxid and a.personId=b.personId
    ) b
    on a.personId  = b.personId;

如果您有任何问题,请与我们联系。

答案 1 :(得分:1)

您需要先从payment表中选择最大值,然后再进行加入:

SELECT a.paymentPending, b.personName FROM 
(select personId, max(paymentPending) as paymentPending 
  from personPayment group by personId) as a, 
personInfo b
 WHERE a.personId  = b.personId ;