0

是否可以使用关键字来按结果在数据表中出现的次数对我的 SELECT QUERY 中的结果进行排序?

MySQL:

  SELECT * FROM interests ORDER BY (keyword)

表值:

hiking
running
swimming
hiking
photography
swimming
hiking

如果返回它们的顺序基于表中每个值出现的频率,它将是:

hiking
hiking
hiking
swimming
swimming
running
photography

如果没有一个特定的关键字,我如何使用 SQL 来实现这一点?

谢谢

4

3 回答 3

5
SELECT COUNT(keyword) AS cnt, keyword
FROM interested
GROUP BY keyword
ORDER BY cnt

会按升序为您提供每个关键字的计数。但是你不会得到 3 个远足条目,2 个游泳,等等......只是hiking,3,,swimming,2等等......

于 2013-02-08T18:16:43.953 回答
4
SELECT  a.*
FROM    interests a
        INNER JOIN 
        (
            SELECT  keyword, COUNT(*) totalCount
            FROm    interests
            GROUP BY keyword
        ) b ON a.keyword = b.keyword
ORDER   BY b.totalCount DESC
于 2013-02-08T18:18:23.897 回答
0
    SELECT 
    t1.*,count(t1.keyword) 
    FROM 
    interests AS t1 INNER JOIN (
     SELECT 
            keyword,count(*) totalcount 
      FROM 
            interests GROUP BY keyword
      )t2 
ON t1.keyword=t2.keyword group by t1.keyword 
   ORDER BY t2.totalcount DESC

Sql Fiddle 演示

于 2013-02-08T19:55:42.840 回答