2016-08-21 39 views
1

正如我得到一排,我也想要抓住該低於所選行中和值的行的一個單獨的計數的行數屬於上述所選擇的行的值。MySQL的GET計數

什麼是這樣做的最佳方法是什麼?

下顯然是錯誤的,但可能說明我的意思......

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 ) VALUES(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 
+0

給出一個示例數據和示例結果。 –

回答

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; 
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