MySQL Forums
Forum List  »  PHP

Select fields using Rand(1) + Group by "BLOCK"
Posted by: Andrei Andrade
Date: April 07, 2014 08:16AM

Hello All,

I am getting crazy about this query that I am trying to do.
I have Google it, forums but unfortunately no luck to find the solution.

Let me explain what I am trying to achieve:

I have this table:

+----------+-------------+
|Advert_Id | Advert_Type |
+----------+-------------+
| 1 | 1 |
| 2 | 3 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
| 6 | 3 |
| 7 | 1 |
| 8 | 1 |
| 9 | 1 |
| 10 | 1 |
| 11 | 1 |
| 12 | 1 |
+----------+-------------+

What I need:

Return Rand Advert_Id but ORDER BY Advert_Type IN "BLOCKS" OF 4 (by 3,2,1 and 1)
So, firt block 3,2,1,1 second 3,2,1,1 and so on... if does not have enough records with 3 or 2 it remain the same and return the others.

+----------+-------------+
|Advert_Id | Advert_Type |
+----------+-------------+
| 2 | 3 |
| 4 | 2 |
| 9 | 1 |
| 12 | 1 |
| 6 | 3 |
| 5 | 2 |
| 1 | 1 |
| 8 | 1 |
| 10 | 1 |
| 3 | 1 |
| 11 | 1 |
| 7 | 1 |
+----------+-------------+

Did you understand what I am trying to do? I can do it with PHP using arrays but I was wondering if is possible to do by SQL query?

thanks again,

Andrei

Options: ReplyQuote


Subject
Written By
Posted
Select fields using Rand(1) + Group by "BLOCK"
April 07, 2014 08:16AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.