2010-12-08 121 views
4

我希望分頁腳本能夠正常工作,但情況有點複雜。我需要從兩個SQL查詢的聯合中選擇數據。請參閱下面的查詢。我有一本桌子書和一本桌子書。我想要的是在這裏按照人氣順序顯示特定類別的所有書籍。通過加入餐桌書和書籍,我通過至少一次訪問獲取所有書籍的數據。然後將它與所有沒有訪問的書籍結合起來。一切正常,但當我嘗試做分頁時,我需要將它限制爲(0,10)(10,10)(20,10)(30,10),對嗎?如果我有9本書籍用於該類別,3761本書沒有任何訪問(總共3770本書),它應該列出377頁,每頁上有10本書。但它不顯示任何數據,因爲它試圖顯示限制3760,10的書籍,因此沒有聯合記錄中的第二個查詢。可能是我無法清除這裏的情況,但如果你對情況有所瞭解,你會明白我的觀點。mysql聯盟限制問題

SELECT * FROM ( 
SELECT * FROM (
SELECT viewcount, b.isbn, booktitle, stock_status, price, description FROM book AS b 
INNER JOIN bookvisit AS bv ON b.isbn = bv.isbn WHERE b.price <> 0 AND hcategoryid = '25' 
ORDER BY viewcount DESC 
LIMIT 10, 10 
) AS t1 
UNION 
SELECT * FROM 
( 
SELECT viewcount, b.isbn, booktitle, stock_status, price, description FROM book AS b 
LEFT JOIN bookvisit AS bv ON b.isbn = bv.isbn WHERE b.price <> 0 AND hcategoryid = '25' 
AND viewcount IS NULL 
ORDER BY viewcount DESC 
LIMIT 10, 10 
) AS t2 
) 
    AS qry 
    ORDER BY viewcount DESC 
LIMIT 10 

回答

2

不要對單獨的查詢使用限制。僅在最後使用限制。您希望從2個查詢中獲得洞結果集,然後僅顯示您需要的10個結果,無論這是限制0,10還是極限3760,10

SELECT * FROM ( 
SELECT * FROM ( 
    SELECT viewcount, b.isbn, booktitle, stock_status, price, description FROM book AS b 
    INNER JOIN bookvisit AS bv ON b.isbn = bv.isbn WHERE b.price <> 0 AND hcategoryid = '25' 
    ORDER BY viewcount DESC 
) AS t1 
UNION 
SELECT * FROM 
( 
    SELECT viewcount, b.isbn, booktitle, stock_status, price, description FROM book AS b 
    LEFT JOIN bookvisit AS bv ON b.isbn = bv.isbn WHERE b.price <> 0 AND hcategoryid = '25' 
    AND viewcount IS NULL 
    ORDER BY viewcount DESC 
) AS t2 
) 
AS qry 
ORDER BY viewcount DESC 
LIMIT 10, 10 
+0

不,它可能會顯示10,000個結果將不得不使用限制 – 2010-12-08 12:27:13