Search code examples
phpmysqlsql-order-by

Mysql ORDER BY COUNT each value on every column field


Each table field is set as 00 00 00 00 00 00. I am trying to find a solution to order by count each of the 00 00 00 00 00 00 number in each column field. The code below works ok but it is ugly and I am not able to order the results. Thanks!

DESIRED RESULT (example)

Number - Times it appears in column

  • 01 - 100
  • 02 - 99
  • 03 - 98

COLUMN SAMPLE

enter image description here

if ($stmt = $post_con->prepare('SELECT asw FROM tb WHERE CONCAT(" ", asw, " ") LIKE CONCAT("% ", ?, " %")')) {


    for($i = 1; $i < 60; $i++){

                $stmt->bind_param("s", $de);
                $de = sprintf('%02d', $i);

                $stmt->execute();
                $stmt->store_result();
                $qty = $stmt->num_rows;

                /* bind result variables */
                $stmt->bind_result($asw);
                $stmt->fetch();

                echo $qty.' -> '.$de.'</br>';

                $stmt->close();


        }   

Solution

  • You can use SQL to do more of the work for you. You can apply the query from this question to your situation.

    The subquery breaks all the numbers into their own row. It uses the SELECT 1 UNION ALL ... SELECT 6 to find the 1st number, ..., and the 6th number and put each one into its own row. (Note that you have to go up to 6 because you have 6 numbers per row. If you had more, you would have to adjust the query accordingly.)

    From there it's as simple as GROUP BY on the number, COUNT()ing the unique occurrences, and ORDER BY the number in ASCending order.

    SELECT num, COUNT(num)
    FROM (
      SELECT
        SUBSTRING_INDEX(SUBSTRING_INDEX(tb.asw, ' ', numbers.n), ' ', -1) num
      FROM
        (SELECT 1 n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6
        ) AS numbers
      INNER JOIN tb
        ON CHAR_LENGTH(tb.asw)
           -CHAR_LENGTH(REPLACE(tb.asw, ' ', ''))>=numbers.n-1
    ) numNumbers
    GROUP BY num
    ORDER BY num ASC