문제

Product 테이블 :

id: int
name: varchar(255)
info: varchar(8000)
.

이름별로 그룹화 된 모든 제품의 목록을 가져와야하며 일부 제품이 같은 이름을 가지고있는 경우 info 필드에서 가장 많은 데이터가 표시되도록 선택해야합니다.또 다른 요구 사항은 일관성이며, 동일한 제품을 매번 표시 할 수 있어야합니다.그러나 성과는이 모든 것에 대한 내 관심사가 아닙니다.

그래서 지금까지 우리가 지금까지 나타났습니다 :

select * from (select * from product order by length(info) desc) as product group by name
.

이 MySQL에서 이 작동하지만 결과를 보장하지는 않습니다.

더 좋은 방법이 있습니까?

업데이트 :

내가 찾고있는 것의 예.데이터가 인 경우

1, 'Product1', '12345'
2, 'Product1', '123'
3, 'Product2', '123456'
4, 'Product2', '123456'
5, 'Product2', '12'
.

예상 결과는 다음 중 하나 여야합니다 :

1, 'Product1', '12345'
3, 'Product2', '123456'
.

또는

1, 'Product1', '12345'
4, 'Product2', '123456'
.

쿼리를 실행할 때마다 동일한 결과만큼이나 두 개 중 하나를 상관하지 않습니다.

도움이 되었습니까?

해결책

나는 당신이 가입해야한다고 생각합니다 :

select p.*
from product p join
     (select p.name, max(len(info)) as maxinfolen
      from product p
      group by p.name
     ) t
     on p.name = t.name and
        len(p.info) = t.maxinfolen
.

정보에서 최대 길이가 반복되면 이중 복사본을 반환합니다.중복을 제거하려면 외부로 그룹화 할 수 있습니다.

select p.name, max(info)
from product p join
     (select p.name, max(len(info)) as maxinfolen
      from product p
      group by p.name
     ) t
     on p.name = t.name and
        len(p.info) = t.maxinfolen
group by p.name
.

마다 같은 ID를 선택하려고하면 동일한 아이디어를 사용할 수 있습니다.

select p.*
from product p join
     (select p.name, min(id) as minid
      from product p join
           (select p.name, max(len(info)) as maxinfolen
            from product p
            group by p.name
           ) t
           on p.name = t.name and
              len(p.info) = t.maxinfolen
      group by p.name
     ) t
     on p.name = t.name and
        p.id = t.minid
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top