I am stuck on a query..
I have a table of ads..There I have column sort_order and date_added.sort_order is set base on group type.So on my page say I want to show 12 ads by 4 groups.
I want 3 ads have order 1 at top in dec order by date_added.
Then 3 ads have order 2 in dec order by date_added.
Then 3 ads have order 3 in dec order by date_added.
Then 3 ads have order 4 in dec order by date_added.
so on front end it should look like this
Name date_added sort_order
ad1 12-2-2015 1
ad2 11-2-2015 1
ad3 10-2-2015 1
ad4 13-2-2015 2
ad5 12-2-2015 2
ad6 07-2-2015 2
ad7 18-2-2015 3
ad8 10-2-2015 3
ad9 03-2-2015 3
ad10 12-2-2015 4
ad11 08-2-2015 4
ad12 03-2-2015 4
If sort_order=1
have only 2 ads then sort_order=2
can show 4 ads. Is it achievable by single query.Please give a advise.
What I am trying is
Select name,sort_order,date_added form ads order by sort_order ASC,date_added DESC LIMIT 0,12
Its not diving results in equal parts for each group.
This is easiest with union all
:
select t.*
from ((Select name, sort_order, date_added
from ads
where sort_order = 1
order by date_added desc
LIMIT 4
) union all
(Select name, sort_order, date_added
from ads
where sort_order = 2
order by date_added desc
LIMIT 4
) union all
(Select name, sort_order, date_added
from ads
where sort_order = 3
order by date_added desc
LIMIT 4
) union all
(Select name, sort_order, date_added
from ads
where sort_order = 4
order by date_added desc
LIMIT 4
)
) t
order by sort_order, date_added desc;
However, this gets harder if you want 12 rows but might not have the intermediate rows. Allocating the extra values is challenging. Here is one approach:
select s.*
from (select s.*,
(@rn := if(@so = sort_order, @rn + 1,
if(@so := sort_order, 1, 1)
)
) seqnum
from ads s cross join
(select @rn := 0, @so := 0) vars
order by sort_order, date_added desc
) s
where @rn <= 12
order by (case when @rn <= 4 then @rn else @rn + sort_order + 100 end)
limit 12;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.