Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql get top half of table then bottom half of table

Tags:

mysql

I need to get the top half of my table in my first query and in the next query I need the bottom half.

I tried doing this for the top but it wont work

SELECT * FROM t_domains WHERE type_domain='radio' ORDER BY 
date_created DESC LIMIT 0, (COUNT(*) / 2)

I need it as two queries for my function to work.

Anybody have any pointers or tips?

like image 563
8bitcat Avatar asked Jan 29 '26 11:01

8bitcat


2 Answers

I would suggest doing 2 query's:

select count(*) from t_domains

to get the total count, and then get the data you want by using limit and offset:

select * from t_domains limit count/2

for the top and

select * from t_domains offset count/2

for the lower half......

This approach gives you also a way to limit the query's in another situation: what if the table contains 1 million records?

like image 147
JvdBerg Avatar answered Jan 31 '26 01:01

JvdBerg


for first half

 mysql-> SET @n := 0

 mysql-> SELECT *,nnn FROM (
         SELECT *, @n := @n + 1 AS nnn  FROM t_domains   ORDER BY date_created 
         ) AS t
         WHERE nnn <=  ( SELECT COUNT(date_created) / 2  FROM t_domains  ) AND type_domain =    'radio'

for second half, change here WHERE nnn <= this "<" on this ">"

like image 26
Oto Shavadze Avatar answered Jan 31 '26 01:01

Oto Shavadze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!