MYSQL - 根据某个字段返回最近的5行

时间:2017-11-30 18:56:49

标签: mysql sql greatest-n-per-group

我有一个带有unix时间戳和事物描述的表。该表将为每个事物提供多个条目,所有条目都具有不同的时间戳。我需要为每件事选择最后五个时间戳。

如果我有东西A的100行,东西B的130行和东西C的20行我希望看到每个东西的最后5行 - 查询应返回15条记录。

我已尝试过限制,但这会让我查询中的最后五位。

任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER(MySQL 8.0):

SELECT *
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY time_col DESC) rn
      FROM tab) sub
WHERE rn <= 5;

答案 1 :(得分:0)

对于100行,您可以轻松地执行以下操作:

package crelix.carparadise;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class FunActivity extends AppCompatActivity {
ListView listView;
ArrayList<HashMap<String, String>> postList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fun);

    listView = (ListView) findViewById(R.id.listView);
    getJSON("http://10.10.7.6/Android/Pages/Fun.php");
}


private void getJSON(final String urlWebService) {

    class GetJSON extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            try {
                loadIntoListView(s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(urlWebService);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String json;
                while ((json = bufferedReader.readLine()) != null) {
                    sb.append(json + "\n");
                }
                return sb.toString().trim();
            } catch (Exception e) {
                return null;
            }
        }
    }
    GetJSON getJSON = new GetJSON();
    getJSON.execute();
}

private void loadIntoListView(String json) throws JSONException {
    JSONArray jsonArray = new JSONArray(json);

    for (int i = 0; i < jsonArray.length(); i++) {

        JSONObject posts = jsonArray.getJSONObject(i);
        String id = posts.getString("id");
        String title = posts.getString("title");
        String image = posts.getString("image");
        String upvotes = posts.getString("upvotes");
        String downvotes = posts.getString("downvotes");
        String comments = posts.getString("comments");
        String share = posts.getString("share");
        String report = posts.getString("report");
        String date = posts.getString("date");
        String addedby = posts.getString("addedby");


        // tmp hash map for single contact
        HashMap<String, String> post = new HashMap<>();

        // adding each child node to HashMap key => value
        post.put("id", id);
        post.put("title", title);
        post.put("image", image);
        post.put("upvotes", upvotes);
        post.put("downvotes", downvotes);
        post.put("comments", comments);
        post.put("share", share);
        post.put("report", report);
        post.put("date", date);
        post.put("addedby", addedby);

        // adding contact to contact list
        postList.add(post);
    }

    ListAdapter adapter = new SimpleAdapter(FunActivity.this, postList,
            R.layout.fun_posts, new String[]{ "title","image","upvotes","downvotes","comments","share","report","date","addedby"},
            new int[]{R.id.titleTv, R.id.imageBtn, R.id.upvoteBtn, R.id.downvoteBtn, R.id.commentBtn, R.id.shareBtn, R.id.reportBtn, R.id.date, R.id.addedbyBtn});
    listView.setAdapter(adapter);

}
}