SELECT *
FROM student as std LEFT JOIN
(SELECT * FROM billing WHERE `paid` < '4' ) AS bill
ON bill.reg_id = std.reg_id
GROUP BY bill.reg_id
ORDER BY bill.id
此处学生表是主表,其主键是计费表中的外键。 记帐表中有多个记录与学生reg_id。
我想要最新的结算记录,限制为1 学生桌上没有限制。
答案 0 :(得分:0)
尝试此查询,我认为它应该有效
SELECT *
FROM student as std LEFT JOIN
(SELECT * FROM billing WHERE `paid` < '4' group by reg_id order by id desc)
AS bill
ON bill.reg_id = std.reg_id
答案 1 :(得分:0)
我假设有一个名为billing_date的列,您必须使用正确的时间戳更新查询。这样可以根据每个结算记录的新近度给出每个结算记录的排名,然后再撤回最近的结算记录。它假设是mysql 8.0,你可以在早期版本中模仿它。
select
*
from student std
left join (select
*, row_number() over (partition by reg_id order by billing_date desc) rn
from billing) bill on bill.reg_id = std.reg_id and rn=1