質問

Product テーブル:

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

すべての製品のリストを名前でグループ化して取得する必要があります。同じ名前の製品がある場合は、最も多くのデータを含む製品が表示されます。 info フィールドを選択して表示する必要があります。もう 1 つの要件は一貫性です。同じ商品が毎回表示されることが保証される必要があります。しかし、これに関してはパフォーマンスはまったく気にしていません。

したがって、これまでに私が思いついた最高のものは次のとおりです。

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'

クエリを実行するたびに同じ結果が得られる限り、2 つのうちのどちらでも構いません。

役に立ちましたか?

解決

結合を行う必要があると思います:

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

info 内で最大長が繰り返される場合、これは重複を返します。重複を排除するには、外側でグループ化できます。

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