我想得到每个用户和他们最后一次付款。我在这里有 2 张桌子users
和finances
。我尝试添加groupby
并得到了我想要的结果,但是它获得了另一个表中最旧的记录。有谁知道我怎么能做到这一点?
我的第一个查询
SELECT users.name, users.email, users.phone, users.parent_id, users.section_id, finances.amount, finances.description, schoolyears.name, finances.date
from users
JOIN finances on users.id = finances.user_id
JOIN schoolyears on users.school_id = schoolyears.school_id
ORDER BY finances.date DESC;
结果我得到
+-----------------+------------------------------+--------------------+-----------+------------+--------+--------------+--------------+------------+
| name | email | phone | parent_id | section_id | amount | description | name | date |
+-----------------+------------------------------+--------------------+-----------+------------+--------+--------------+--------------+------------+
| Madelynn Stokes | moore.dominic@cartwright.com | +63 (971) 659-8143 | 10 | NULL | 1000 | New Payables | SY-2019-2020 | 2019-11-14 |
| Annamarie Morar | emile99@hotmail.com | (0997) 212-7919 | 3 | NULL | 500 | New Pays | SY-2019-2020 | 2019-11-14 |
| Madelynn Stokes | moore.dominic@cartwright.com | +63 (971) 659-8143 | 10 | NULL | 5000 | Old Payables | SY-2019-2020 | 2019-11-13 |
| Annamarie Morar | emile99@hotmail.com | (0997) 212-7919 | 3 | NULL | 200 | Old Pays | SY-2019-2020 | 2019-11-13 |
+-----------------+------------------------------+--------------------+-----------+------------+--------+--------------+--------------+------------+
我只想要其他表中的最新记录。新应付款和新支付。
我尝试了第二个查询
SELECT users.name, users.email, users.phone, users.parent_id, users.section_id, finances.amount, finances.description, schoolyears.name, finances.date
from users
JOIN finances on users.id = finances.user_id
JOIN schoolyears on users.school_id = schoolyears.school_id
GROUP BY users.id
ORDER BY finances.date DESC;
它有效,但我得到了最古老的记录。
+-----------------+------------------------------+--------------------+-----------+------------+--------+--------------+--------------+------------+
| name | email | phone | parent_id | section_id | amount | description | name | date |
+-----------------+------------------------------+--------------------+-----------+------------+--------+--------------+--------------+------------+
| Madelynn Stokes | moore.dominic@cartwright.com | +63 (971) 659-8143 | 10 | NULL | 5000 | Old Payables | SY-2019-2020 | 2019-11-13 |
| Annamarie Morar | emile99@hotmail.com | (0997) 212-7919 | 3 | NULL | 200 | Old Pays | SY-2019-2020 | 2019-11-13 |
+-----------------+------------------------------+--------------------+-----------+------------+--------+--------------+--------------+------------+