mysql获取一行中具有高于和低于某个值的值的列数

时间:2016-08-21 23:43:39

标签: mysql

当我得到一行时,我还想获取低于所选行中某个值的行数以及高于所选行值的单独行数。

这样做的最佳方法是什么?

以下显然是错误的,但可能会说明我的意思......

SELECT page.*,COUNT(less_than_threshold.id) as `smaller`,    
COUNT(greater_than_threshold.id) as `bigger`

FROM `learning_pages` as pages

JOIN learning_pages as less_than_threshhold on page.class_id=less_than_threshold.class_id 
AND less_than_threshhold.content_count < page.content_count

JOIN learning_pages as greater_than_threshold ON 
page.class_id=greater_than_threshold.class_id AND 
greater_than_threshold.content_count>page.content_count

WHERE page.id=5

修改的 根据要求:

learning_pages
id (BIG INT) | content_count (INT) | type (VARCHAR) | author_id (BIG INT) | date_updated (DATETIME)| class_id(BIG_INT)

截断值

(ID,CONTENT_COUNT)    价值观(1,3),(2,4),(3,3),(4,5),(5,3),(6,2),(7,1),(8,3),( 9,2)   ...

SELECT page.*,COUNT(less_than_threshold.id) as `smaller`
FROM `learning_pages` as pages

JOIN learning_pages as less_than_threshhold on page.class_id=less_than_threshold.class_id 
AND less_than_threshhold.content_count < page.content_count

WHERE page.id=5

我的smaller计数为3,这是正确的。将bigger计数添加到该问题是个问题。我的解决方案是sub_query,我担心这不是最好的解决方案......

 SELECT page.*, count(i.id) as `bigger` FROM 
(SELECT lp.*,COUNT(clp.id) as `smaller` FROM `learning_pages` as lp 
JOIN learning_pages as clp on lp.class_id=clp.class_id AND 
clp.content_count<lp.content_count WHERE lp.id=5) as page 

JOIN learning_pages as i ON page.class_id =i.class_id WHERE page.id=5 

2 个答案:

答案 0 :(得分:1)

您可以DISTINCT结果。使用以下查询:

SELECT page.*,
COUNT( DISTINCT less_than_threshold.id) as `smaller`,    
COUNT( DISTINCT greater_than_threshold.id) as `bigger`

FROM `learning_pages` as page

JOIN learning_pages as less_than_threshold 
on page.class_id=less_than_threshold.class_id 
AND less_than_threshold.content_count < page.content_count

JOIN learning_pages as greater_than_threshold 
ON page.class_id=greater_than_threshold.class_id 
AND greater_than_threshold.content_count>page.content_count

WHERE page.id=5

答案 1 :(得分:0)

你可以在select语句中使用查询来尝试这样的事情:

SELECT pages.*,
    (
        SELECT COUNT(*)
        FROM pages
        WHERE pages.id < 5
    ) AS less_than_threshold,
    (
        SELECT COUNT(*)
        FROM pages
        WHERE pages.id > 5
    ) AS greater_than_threshold
FROM pages
WHERE pages.id = 5;