[英]How do I select record from mysql database based on the longest 'string' in one filed when grouping?
这是我的桌子:
ID Title Content Cluster
1 a abc 1
2 b abcde 1
3 c abcde 1
4 d abc 2
5 e abcdef 2
我想根据字段内容中最长的“字符串”选择记录,然后按群集分组。 我怎样才能做到这一点。
预期的结果:
ID Title Content Cluster
3 c abcde 1
5 e abcdef 2
怎么做?
使用自连接,您可以找出每个集群中具有最大长度的所有行:
select a.*
from my_table a
left join my_table b
on a.cluster = b.cluster
and length(a.content) < length(b.content)
where b.cluster is null;
另一种方法是在子查询中使用分组依据:
select a.*
from my_table a
inner join (
select cluster, max(length(content)) len
from my_table
group by cluster
) b on a.cluster = b.cluster and length(a.content) = b.len;
另外,如果内容包含Unicode字符,则使用char_length
而不是length
函数。
为了使长度保持一致,您可以获取ID最高(或根据需要最低的ID)的行:
select a.*
from cluster_sosial a
left join cluster_sosial b
on a.cluster = b.cluster
and (
length(a.content) < length(b.content)
or (length(a.content) = length(b.content) and a.cluster_sosial_id < b.cluster_sosial_id)
)
where b.cluster is null;
使用相关子查询
SELECT
*
FROM
cluster_sosial a
WHERE
cluster_sosial_id = (SELECT
cluster_sosial_id
FROM
cluster_sosial B
WHERE
a.Cluster = b.Cluster
ORDER BY LENGTH(content) DESC , cluster_sosial_id DESC
LIMIT 1)
这是使用EXISTS
一种方法
SELECT *
FROM Yourtable a
WHERE EXISTS (SELECT 1
FROM Yourtable B
WHERE a.Cluster = b.Cluster
HAVING Max(Len(b.Content)) = Len(a.Content))
要么
SELECT *
FROM yourtable a
WHERE Content = (SELECT content
FROM yourtable B
WHERE a.Cluster = b.Cluster
ORDER BY Len(content) DESC Limit 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.