D
D
Dmitry Labutin2015-08-02 08:32:49
MySQL
Dmitry Labutin, 2015-08-02 08:32:49

How to write a MySQL query so that rows with the same field value are in a row, but not sorted?

Suppose there is a table:
Field1 Name
------------
1 Vasya
2 Petya
1 Olya
3 Oleg
2 Kolya
I want to write a query that will display ALL rows so that rows with the same Field1 go in a row, BUT Field1 were sorted (let it be random)
For example, the output could be:
Field1 Name
------------
2 Petya
2 Kolya
1 Vasya
1 Olya
3 Oleg
Once again: it is important that lines with the same Field1 go in a row, but the values ​​of Field1 themselves were in random order.
In a real table, there are 80 million rows, which have about 2000 different values ​​of Field1.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
svd71, 2015-08-02
@svd71

Quasi-sorting is almost impossible to do in any DBMS. More precisely, you can do what you formulate correctly.
Try sorting with imaginary calculated fields:

Select * from table1 
order by cast(field1 as varchar(5))+field2

D
dk-web, 2015-08-02
@dk-web

I don’t know how to use such a request .. but the result was achieved - though on 10 names)

$q="SELECT DISTINCT field1 FROM names ";
         $res=mysql_query($q) or die ('о'.mysql_error());
          $data=array();
          while ($row=mysql_fetch_assoc($res)) {
                $data[$row['field1']]=$row['field1'];
          }  
                
        $keys=array_keys($data); //массив уникальных ключей

        shuffle($keys); //случайный порядок

        foreach ($keys as $key=>$value) {
       
        $q="SELECT * FROM names WHERE field1=".$value."";
        
        $res=mysql_query($q) or die ('о'.mysql_error());
          $data_names=array();
          
          while ($row=mysql_fetch_assoc($res)) {
                $data_names[]=$row['name'];
          }  
          $data_need[$value]=$data_names;
}


echo '<pre>';
print_r ($data_need);
echo '</pre>';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question