dqp4933 2014-08-15 13:23
浏览 118
已采纳

数据库查询选择两个表,按日期排序和限制[重复]

Is it possible to do a query like I described in the title? I have two tables with different types of columns, nothing similar between them. What I want to do is join them together and display them in reversing order starting with the earliest but limiting to 5 per page. The way I'm getting the number of items is like this:

$limit = 5;
$page = 1;
if(isset($_GET['pn'])) {
    $page = $_GET['pn'];
    $lim = ($page-1)*$limit;
}else{
    $lim = ($page-1)*$limit;
}
$l = mysqli_query($mysqli_connect, "SELECT id FROM table1");
$s = mysqli_query($mysqli_connect, "SELECT id FROM table2");
$r = mysqli_num_rows($l) + mysqli_num_rows($s);

Then I'm just adding the page number in the URL if the user clicks next. Right now to get the query from one table I'm doing this:

$sql = mysqli_query($mysqli_connect, "SELECT * FROM table1 ORDER BY dateadded desc LIMIT $lim, $limit");

I need help constructing a query that will select both tables...and how to keep track of which rows were already added using the LIMIT?

UPDATE:

$sql = mysqli_query($mysqli_connect, "SELECT id FROM (SELECT id, dateadded FROM table1 UNION SELECT id, dateadded FROM table2) ORDER BY dateadded LIMIT $lim, $limit");
$num_rows = mysqli_num_rows($sql);
echo $num_rows;

I get a warning saying mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in.... Can't I see how many items were returned???

</div>
  • 写回答

2条回答 默认 最新

  • doutong1890 2014-08-15 13:31
    关注

    I assume at least both your table have an id and a field with the date (dateadded)

    So first I would retrieve the ids you need to display with a query like this for the first page.

    SELECT id FROM (
    SELECT id, dateadded FROM table1
    UNION
    SELECT id, dateadded FROM table2
    ) AS mergedtable ORDER BY dateadded LIMIT 0, 5;
    

    Based on the ids retrieved, you can query your database to get all the information from the tables

    SELECT * FROM table1 WHERE id IN ( /* list of ids */ );
    SELECT * FROM table2 WHERE id IN ( /* list of ids */ );
    

    And then you will have to make a php manipulation to merge your results and order then based on their date. You might need also to prefix your ids based on their origin table if they are based on two different sequences

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 qgcomp混合物线性模型分析的代码出现错误:Model aliasing occurred
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'