简体   繁体   English

mysql:如何从重复的行组中按2列获取最大id?

[英]mysql:how to get max id from duplicated row group by 2 columns?

I have one table name "sections_content" that has the following columns 我有一个表名称“ sections_content”,其中包含以下各列

在此处输入图片说明

and I want to get max id for each statecode and policyname 我想获取每个状态码和策略名称的最大ID

So ,for example,the result of statecode CN / IL /IE should be 因此,例如,状态码CN / IL / IE的结果应为

在此处输入图片说明

How should I write the code for mysql ? 我应该如何为mysql编写代码?

thanks. 谢谢。

I think you can solve this with a JOIN on the MAX for that group: 我认为您可以通过在该组的MAXJOIN来解决此问题:

SELECT * FROM sections_content as t
JOIN
    (
        SELECT MAX(id) as id
        FROM sections_content AS tbl
        GROUP BY
            tbl.policyName,
            tbl.statecode
    ) AS maxId
    ON maxId.id=t.id

I think you can use ORDER BY and LIMIT keywords to get the maximum number. 我认为您可以使用ORDER BYLIMIT关键字来获取最大数量。

Exp: Having tables; Exp:有桌子; table1 and table2 as in your database. table1table2就像在数据库中一样。 check below queries. 检查以下查询。

SELECT table1.id, table2.statecode, table2.policyname, sections_content.student_lga_of_origin 
FROM table1
JOIN table2
ON table1.policyname = table2.policyname
ORDER BY table1.id DESC
LIMIT 1
OFFSET 1

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

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