sql >> データベース >  >> RDS >> Mysql

mysqlgroupbyおよび左結合で2番目に高い値を取得する方法

    まず、3回目の参加はまったく必要ありません。 1つの結合で計算を行うことができます:

    from (select id
          from owner
          where date_format(auction_date,'%Y-%m-%d %H:%i:00') = date_format(NOW(),'%Y-%m-%d %H:%i:00')
         ) as a left join
         (select owner_id, max(nb) as maxbid, max(mb) as maxautobi
          from auction
          group by owner_id
         ) b
         on a.id=b.owner_id;
    

    mbの2番目に大きい値を取得する 次に、substring_index()を含むトリックを使用します およびgroup_concat()

       from (select id
              from owner
              where date_format(auction_date,'%Y-%m-%d %H:%i:00') = date_format(NOW(),'%Y-%m-%d %H:%i:00')
             ) as a left join
             (select owner_id, max(nb) as maxbid, max(mb) as maxautobi,
                     substring_index(substring_index(group_concat(mb order by mb desc), ',', 2), ',', -1
                                    ) as second_mb
              from auction
              group by owner_id
             ) b
             on a.id=b.owner_id;
    

    アイデアは、mbの順序で、値を連結することです。 。次に、リストの2番目の要素を取得します。欠点の1つは、数値で始まる場合でも、値が文字列に変換されることです。




    1. MySQLデータベースの変更を追跡するためのトリガー

    2. エラー1062(23000):キー「PRIMARY」のエントリ「2147483647」が重複しています

    3. 2つの文字列が1文字異なっていても、どうすれば一致させることができますか?

    4. JPAで2つの日付の間の日数をカウントします