在SQL中使用ORDER BY子句

时间:2013-02-08 18:15:11

标签: mysql sql

是否可以使用一个关键字,按照它们在数据表中显示的次数,将SELECT QUERY中的结果排序?

MySQL的:

  SELECT * FROM interests ORDER BY (keyword)

表值:

hiking
running
swimming
hiking
photography
swimming
hiking

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

hiking
hiking
hiking
swimming
swimming
running
photography

如果没有特定的关键字,我怎样才能用SQL实现这个?

由于

3 个答案:

答案 0 :(得分:5)

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

会按升序给出每个关键字的计数。但你不会得到3个徒步旅行,2次游览等等......只是hiking,3swimming,2等......

答案 1 :(得分: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

答案 2 :(得分: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 demo