正如我得到一排,我也想要抓住該低於所選行中和值的行的一個單獨的計數的行數屬於上述所選擇的行的值。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
給出一個示例數據和示例結果。 –