简体   繁体   English

MySQL为表中的每个ID选择最新的1行

[英]MySQL Select latest 1 row for each ID in table

I have a table called sw_practice populated with organisations, and a second table called sw_invoices with the invoice data for each organisation. 我有一个名为sw_practice的表,其中填充了组织,还有一个名为sw_invoices的表,其中包含每个组织的发票数据。

Within sw_invoices, there could be several invoices (there is an incremental unique ID column) linked to the organisations with their own ID (Prac_ID). 在sw_invoices中,可能有多个发票(具有递增的唯一ID列)与具有自己的ID(Prac_ID)的组织链接。

I am trying to get a list of all organisations (whether they've been invoiced or not) but only 1 entry per organisation, so if they HAVE been invoiced, only the latest shows. 我正在尝试获取所有组织的清单(无论是否已开具发票),但每个组织只有1个条目,因此,如果已开具发票,则仅显示最新展览。

I have tried: 我努力了:

SELECT * FROM sw_practices as p LEFT JOIN sw_invoices as i ON p.Prac_ID = i.Prac_ID WHERE p.Active = '2' ORDER BY i.Inv_ID DESC LIMIT 1

but this only shows the latest row out of them all. 但这仅显示所有这些中的最新行。

And if I remove LIMIT 1 from the end it does show all of the data but shows more than 1 entry for some organisations. 而且,如果我从末尾删除LIMIT 1,它会显示所有数据,但对于某些组织会显示多个条目。

I'd like the query to say "select all from sw_practices WHERE Active = 2 and show their invoice data but only show the latest 1 for each different Prac_ID" 我希望查询说“从sw_practices WHERE Active = 2中全选并显示其发票数据,但对于每个不同的Prac_ID仅显示最新的1”

使用分组依据:

SELECT * FROM sw_practices as p LEFT JOIN (Select * FROM sw_invoices ORDER BY Prac_ID DESC )as i ON p.Prac_ID = i.Prac_ID WHERE p.Active = '2' GROUP BY p.Prac_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM