-1

enter image description here

Here i get mos popular hashtags (mos used hashtags) but problem is with comma my query show this:

Popular hashtags: 
#q7 (2)
#q9 (2)
#q7 , #q0 (1)
#q0 (1)

I want this:

Popular hashtags: 
#q7 (3 times )
#q9 (2 times)
#q0 (2 times)

my code:

$query_result = mysqli_query($Connection, "select hashtag, count(hashtag) as cnt
from tricks
group by hashtag
order by cnt desc limit 5");

$results = array();
while($row = mysqli_fetch_assoc($query_result)) {
   $results[] = "{$row['hashtag']} ({$row['cnt']})";
}
echo "Popular hashtags: </br>", implode("</br>", $results);

3 Answers3

1

Php solution:

$query_result = mysqli_query($Connection, 
                  "SELECT hashtag FROM tricks");             

$popularHashtags = array();

while($row = mysqli_fetch_assoc($query_result)) {

  $hashtags = explode(',', $row['hashtag']);

  foreach($hashtags as $hashtag) {
      $hashtag = trim($hashtag);

      if (!empty($hashtag)) {

        if (!isset($popularHashtags[$hashtag])) {
          $popularHashtags[$hashtag] = 0;
        }

        $popularHashtags[$hashtag]++;
      } 
  }
}


arsort($popularHashtags);

// for showing popular hashtags

echo "Popular hashtags: <br />";

foreach($popularHashtags as $hashtag => $total) {
  echo $hashtag . " ( " . $total . " ) <br />";
}
Depzor
  • 1,126
  • 1
  • 12
  • 21
0

If you know the number of hastags contained in the field, you can use the SUBSTRING_INDEX function, or you can see this answer MySQL split to split your field.

Something like this (I have not a MySQL instance):

SELECT hastag as T1 FROM tricks WHERE hastag NOT LIKE '%,%' -- Take the Hastag without separator in it
UNION
SELECT SUBSTRING_INDEX(hashtag, ',', 1) as T1 FROM tricks WHERE hastag LIKE '%,%' -- Take the first Hastag (before separator)
UNION
SELECT SUBSTRING_INDEX(hashtag, ',', 2) as T1 FROM tricks WHERE hastag LIKE '%,%' -- Take the second Hastag (before separator) 
Community
  • 1
  • 1
Alberto
  • 71
  • 1
  • 7
0

Try this out

select count(*) as total, hashtag FROM (
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(hashtag, ',', n.n), ',', -1) hashtag
  FROM table CROSS JOIN 
(
   SELECT a.N + b.N * 10 + 1 n
     FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
   ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ORDER BY n
) n WHERE n.n <= 1 + (LENGTH(hashtag) - LENGTH(REPLACE(hashtag, ',', ''))) ORDER BY hashtag ) alias GROUP by hashtag

Took the help from this answer. Hope this helps you

Community
  • 1
  • 1