mysql union限制问题

时间:2010-12-08 10:03:13

标签: mysql pagination paging union limit

我希望分页脚本基本上正常工作,但情况有点复杂。我需要从两个sql查询的联合中选择数据。请参阅下面的查询。我有一本桌子书和一本桌子书。我想要的是在这里按照人气顺序显示特定类别的所有书籍。我通过加入table book和bookvisit来获取至少一次访问的所有书籍的数据。然后将它与所有没有访问的书籍联合起来。一切正常,但当我尝试分页时,我需要限制它像(0,10)(10,10)(20,10)(30,10),对吗?如果我在该类别的书签中有9本书,并且没有任何访问该类别的3761本书(总共3770本书),则应该列出377页,每页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 
 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 个答案:

答案 0 :(得分:3)

不要对单独的查询使用限制。仅在最后使用限制。您希望从2个查询中获取孔结果集,然后仅显示您需要的10个结果,无论这是LIMIT 0,10还是LIMIT 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

答案 1 :(得分:0)

旧的,但仍然有意义。

基本上,从性能角度考虑,必须对UNION涉及的每个查询使用LIMIT,如果您知道结果集之间将不存在重复,则应考虑在性能方面考虑使用UNION ALL。然后,如果需要,比如说LIMIT 100、20,则对每个查询都用120(OFFSET + LIMIT)进行LIMIT,则总是获取所需记录的两倍,但不是全部。

SELECT [fields] FROM
(
   (SELECT [fields] FROM ... LIMIT 10)
   UNION ALL
   (SELECT [fields] FROM ... LIMIT 10)
) query
LIMIT 0, 10

第5页

SELECT [fields] FROM
(
   (SELECT [fields] FROM ... LIMIT 50)
   UNION ALL
   (SELECT [fields] FROM ... LIMIT 50)
) query
LIMIT 40, 10