简体   繁体   中英

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

在此处输入图片说明

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();


        }   

Something more of best practice would be but hard to tell without more details as per what you are looking for:

$stmt = $post_con->prepare('SELECT asw, count(asw) as count FROM tb WHERE CONCAT(" ", asw, " ") LIKE CONCAT("% ", ?, " %") GROUP BY asw ORDER BY count DESC LIMIT 1');
for ($i = 1; $i < 60; $i++) {
    $stmt->bind_param(1, sprintf('%02d', $i));
    $stmt->execute();
    $obj = $stmt->fetchall(PDO::FETCH_ASSOC);
    if (count($obj) !== 0) {
        echo $de . '->' . $obj['count'] . '</br>';
    }
}
$stmt->close();

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 ASC ending 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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM