2016-07-20 148 views
2

使用下面的查詢,我可以搜索給定半徑內的屬性並返回結果。MySQL - 在指定HAVING時使用COUNT()返回總計結果

SELECT id, address, (3959 * acos(cos(radians(53.184815)) * cos(radians(lat)) * cos(radians(lng) - radians(-3.025741)) + sin(radians(53.184815)) * sin(radians(lat)))) AS distance 
FROM properties 
WHERE area = 1 HAVING distance <= 1 
ORDER BY price DESC, distance ASC 
LIMIT 0, 10 

但是我現在想添加分頁,因此「LIMIT 0,10」但不知何故讓查詢返回的總成績。例如,如果有100個結果,但我們僅限於前10個結果,則返回總數爲100.

我試着在select後添加「COUNT(*)AS total」,但是這導致了零結果被退回。

如何讓查詢以這種方式返回總數?

+0

SQL_CALC_FOUND_ROWS和SELECT FOUND_ROWS();之後; – splash58

+0

SQL_CALC_FOUND_ROWS顯然最多慢10倍:http://stackoverflow.com/questions/186588/which-is-fastest-select-sql-calc-found-rows-from-table-or-select-count – Reado

+0

total means ,行數或總屬性爲數字? – Avishake

回答

2

我認爲這將需要一個子查詢來實現這一目標:

SELECT 
    id, address, (3959 * acos(cos(radians(53.184815)) * cos(radians(lat)) * cos(radians(lng) - radians(-3.025741)) + sin(radians(53.184815)) * sin(radians(lat)))) AS distance, 
    (SELECT count(*) FROM properties WHERE area = 1 HAVING (3959 * acos(cos(radians(53.184815)) * cos(radians(lat)) * cos(radians(lng) - radians(-3.025741)) + sin(radians(53.184815)) * sin(radians(lat))))<= 1) AS total 
FROM properties 
WHERE area = 1 HAVING distance <= 1 
ORDER BY price DESC, distance ASC 
LIMIT 0, 10 
1

要麼你必須使用一個單獨的查詢,而無需使用次數限制(*)或指示飛濺,在您的查詢,然後發出使用SQL_CALC_FOUND_ROWS一個SELECT FOUND_ROWS();獲得總數。

您可以嘗試在您的主查詢中將count(*)查詢作爲子查詢插入,但對於我來說,這只是查詢的不必要的複雜性。