Php / Mysql Union 和 Limit offset

问题描述 投票:0回答:2

我有3个结构完全相同的表,我需要将它们作为一个大表进行查询,对整个大表进行排序和限制。 当我使用分页时,限制是偏移量。

这是我到目前为止所拥有的:

$from = (($page_number-1)*10);
$to   =  ($page_number)*10;     

$request = mysql_query("
    (SELECT * FROM table_a) 
    UNION ALL 
    (SELECT * FROM table_b) 
    UNION ALL 
    (SELECT * FROM table_c) 
    ORDER BY title ASC 
    LIMIT ".$from.",".$to 
);

$z=0;

while ($result = mysql_fetch_array($request)) 
{
    ....
    $z++;
};

$counter = $z;

我希望 $counter 等于 10,无论页面是什么,但是:

第 1 页,$counter = 10

第 2 页,$counter = 20

第 3 页,$counter = 23

第 4 页,$counter = 3

好吧,如果最后一页不一定等于 10,因为我得到了列表中剩下的内容,但第 2 页和第 3 页的 20 和 23 对我来说没有任何意义。

它必须与 LIMIT 有关,因为如果我只以经典方式使用单个表,我的计数器始终等于 10(当然,除非它是最后一页)。

这里出了什么问题?

谢谢!

mysql request limit union counter
2个回答
7
投票

Limit 应该有你想要的开始和行数。因此,如果您想要前 10 行,请点击

0, 10
,如果您想要接下来的 10 行,请点击
10, 10
(不是
10, 20
,它会给您从第 10 行开始的 20 行)。

如果您仍然遇到问题,请尝试将选择和并集放入它们自己的 () 组中。我不确定操作顺序,您的限制可能仅适用于最后一个表。

$request = mysql_query("
    ( 
    (SELECT * FROM table_a) 
    UNION ALL 
    (SELECT * FROM table_b) 
    UNION ALL 
    (SELECT * FROM table_c)
    ) 
    ORDER BY title ASC 
    LIMIT ".$from.",10
);

0
投票

我会添加关于分页的内容,开头的限制可以固定或改变,具体取决于页面上需要显示的元素数量。

每页固定元素数量:

$start = $curent_page = 0;
$limit = $per_page = 15;
 
if (!empty($_GET['page']) and is_numeric($_GET['page']) and $get_curent_page = filter_var($_GET['page'], FILTER_SANITIZE_STRING))
{
  $curent_page = ((!empty($get_curent_page) and is_numeric($get_curent_page)) ? (int)$get_curent_page : 0);
}

$start = ((is_int($curent_page) and $curent_page > 1) ? (($curent_page-1)*$per_page) : 0);

$request = mysql_query("
( 
(SELECT * FROM table_a) 
UNION ALL 
(SELECT * FROM table_b) 
UNION ALL 
(SELECT * FROM table_c)
) 
ORDER BY title ASC 
LIMIT ".$start.", "$limit");

或者在视图页面上使用过滤器指定限制,25、50、100 项:

$start = $curent_page = 0;
$limit = $per_page = 15;
 
if (!empty($_GET['page']) and is_numeric($_GET['page']) and $get_curent_page = filter_var($_GET['page'], FILTER_SANITIZE_STRING))
{
  $curent_page = ((!empty($get_curent_page) and is_numeric($get_curent_page)) ? (int)$get_curent_page : 0);
}

if (!empty($_GET['limit']) and is_numeric($_GET['limit']) and $get_curent_limit = filter_var($_GET['limit'], FILTER_SANITIZE_STRING))
{
  $curent_limit = ((!empty($get_curent_limit) and is_numeric($get_curent_limit)) ? (int)$get_curent_limit : 0);

  if (is_int($curent_limit) and ($curent_limit <= 100 and $curent_limit > $per_page))
  {
    $limit = $curent_limit;
  }
}

$start = ((is_int($curent_page) and $curent_page > 1) ? (($curent_page-1)*$per_page) : 0);

$request = mysql_query("
( 
(SELECT * FROM table_a) 
UNION ALL 
(SELECT * FROM table_b) 
UNION ALL 
(SELECT * FROM table_c)
) 
ORDER BY title ASC 
LIMIT ".$start.", "$limit");
© www.soinside.com 2019 - 2024. All rights reserved.