Mysql排序数据交替

时间:2018-06-13 09:50:43

标签: mysql sql

我有一个大表,数据的结构如下

struct X { int a; int b; };
bool operator< (X lhs, X rhs) { return lhs.a < rhs.a; }
X x1 {0, 1};
X x2 {0, 2};
auto x3 = std::max(x1, x2); // it's guaranteed that an X which cantains {0, 1} is returned

我希望能够随机显示site_car列,但是第一个twiteite第二个,第三个每个15个或更多个第三个

我要展示的内容

My table car
id_car | Site_car     | descr_car
-----------------------------------
1      | onesite      | onedesc
2      | twosite      | twodesc
3      | twosite      | onedesc
4      | onesite      | onedesc
5      | twosite      | twodesc
6      | onesite      | onedesc
7      | treesite     | onedesc
8      | treesite     | onedesc
你知道吗?

THX

2 个答案:

答案 0 :(得分:0)

这在MySQL中很棘手。我们的想法是枚举行,然后按枚举排序:

select c.*
from (select c.*,
             (@rn := if(@sc = site_car, @rn + 1,
                        if(@sc := site_car, 1, 1)
                       )
             ) as rn
      from (select c.*
            from car c
            order by site_car, id_car
           ) c cross join
           (select @sc := -1, @rn := 0) params
     ) c
order by rn, field(site_car, 'onesite', 'twosite', 'threesite');

顺便说一句,这在MySQL 8 +中简单得多:

select c.*
from car c
order by row_number() over (partition by site_car order by id_car),
         field(site_car, 'onesite', 'twosite', 'threesite');

答案 1 :(得分:0)

你可以试试这个

private Activity activity;
private LayoutInflater inflater;
private List<ClientBookingData> Items;

public CustomClientBookingList(){}

public CustomClientBookingList(Activity activity, List<ClientBookingData> Items) {
    this.activity = activity;
    this.Items = Items;
}


@Override
public int getCount() {
    return Items.size();
}

@Override
public Object getItem(int location) {
    return Items.get(location);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.activity_custom_client_booking_list, null,true);

    TextView bdate = (TextView)convertView.findViewById(R.id.bdate);
    TextView brand = (TextView)convertView.findViewById(R.id.brand);
    TextView carno = (TextView)convertView.findViewById(R.id.carno);
    TextView advance = (TextView)convertView.findViewById(R.id.advance);
    TextView due = (TextView)convertView.findViewById(R.id.due);
    TextView bfees = (TextView)convertView.findViewById(R.id.bfees);

    // getting data for the row
    ClientBookingData m = Items.get(position);

    // set data
    bdate.setText(m.getBdate());
    brand.setText(m.getBrand());
    carno.setText(m.getCarno());
    advance.setText(m.getAdvance());
    due.setText(m.getDue());
    bfees.setText(m.getBfees());

    return convertView;
}