简体   繁体   中英

ordering sql table based on highest number of a piece of data

I have a phpmyadmin table called comments, with fields post_id, username, title, message, location, filename, and filename1. I would like to sort the table with comments with most number of the string "filename1" at the top, and the comments with the least number of the same "filename1" to be towards the bottom. What sql code should I enter into the table to achieve this? Or what piece of code in an android application should I add to achieve this, I can edit the post with android code if necessary.

SELECT post_id , username , title , message , location , filename , filename1 FROM comments WHERE 1

If you want to sort the table with most number of words/strings in the field filename1 . for example:- "hello how ru?" will be at the top and "hello" will be at bottom.

then use this code:

SELECT post_id, username, title, message, location, filename, filename1 FROM comments ORDER BY (LENGTH(filename1) - LENGTH(REPLACE(filename1, ' ', ''))+1) DESC

Assuming that by "most number of string filename1", you mean you want to count the number of occurrences (duplicates) of a particular value of the filename1 column, without regard to which post the comment is associated with...

We'd get the "count" of occurrences with a separate query, and then include that query as a rowsource (as an inline view) in the original query.

For example:

SELECT t.post_id
     , t.username
     , t.title
     , t.message
     , t.location
     , t.filename
     , t.filename1 
  FROM comments t 
  JOIN ( SELECT s.filename1
              , COUNT(1) AS cnt
           FROM comments s
          GROUP BY s.filename1
       ) c
    ON c.filename1 = t.filename1
 WHERE 1
 ORDER
    BY c.cnt DESC
     , c.filename1 DESC
     , t.post_id DESC

If you wanted count of duplicate filename1 values associated with each post, then we'd add s.post_id to the SELECT list and the GROUP BY clause of the inline view, and add an equality predicate on the outer query AND c.post_id = t.post_id .

(Without an example, it's not clear what result set you want returned, so we're just guessing.)

(Note that the equality comparator in the JOIN predicate will filter out rows that have a NULL value for filename1 . If we also want to include NULL values, then we could replace the equality comparator with the null-safe equality comparator:

    ON c.filename1 <=> t.filename1

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