我有一个列,我想从最常值中按降序返回不同的值,而不是匹配某些条件。
该列包含以下记录:
this
those
that
dog
these
here
there
cat
dog
hamster
hamster
there
blah
here
blah
blah
dog
所以我有:
SELECT DISTINCT(rcolumn)
FROM otable
WHERE reason != 'this'
AND reason != 'that'
AND reason != 'those'
AND reason != 'these'
AND reason != 'them'
AND reason != 'here'
AND reason != 'there'
AND reason != 'in between'
AND reason != 'all over'
AND reason != 'something'
AND reason != 'something else'
AND reason != 'anywhere'
AND reason != 'anywhere else'
将返回:
blah
cats
hamsters
dogs
但我希望它能回归:
blah
dogs
hamsters
cats
按顺序,因为blah出现在桌子上,然后是狗,然后是仓鼠,然后是猫。
答案 0 :(得分:1)
为了按频率顺序返回内容,您需要GROUP BY
值:
SELECT rcolumn
FROM otable
-- WHERE stuff
GROUP BY rcolumn;
这应该给出与你所拥有的答案基本相同的答案。然后,您可以轻松计算每行的发生率并进行排序:
SELECT rcolumn, COUNT(*) AS frequency
FROM otable
GROUP BY rcolumn
ORDER BY frequency DESC;
如果您不希望在结果中看到计算出的频率列,那么您可以直接订购:
SELECT rcolumn
FROM otable
GROUP BY rcolumn
ORDER BY COUNT(*) DESC;
通常,在使用GROUP BY
子句时,请注意只选择:
大多数RDBMS会将此视为错误,但MySQL会选择一个随机行并返回该数据。
最后为了更加清晰,为什么不将长WHERE
子句更改为更优雅的内容:
WHERE rcolumn NOT IN
('this'
,'that'
,'those'
-- ...
)
答案 1 :(得分:0)
只需在声明的末尾添加ORDER BY COUNT(rcolumn) DESC
SELECT DISTINCT rcolumn
FROM otable
WHERE reason != 'this'
AND reason != 'that'
AND reason != 'those'
AND reason != 'these'
AND reason != 'them'
AND reason != 'here'
AND reason != 'there'
AND reason != 'in between'
AND reason != 'all over'
AND reason != 'something'
AND reason != 'something else'
AND reason != 'anywhere'
AND reason != 'anywhere else'
ORDER BY COUNT(rcolumn) DESC
;