我正在尝试从两个mysql表中获取数据并按日期排列它们。这两个表与收入和支出有关。我想要实现的是首先从收入表中显示日期为2014年4月15日的数据,然后从支出表中显示日期为15/04/2014的数据,然后再次循环显示下一个日期并显示与收入表和支出表有关的16/04/14数据。现在的代码循环次数为no。收入表中的条目。怎么纠正这个?代码如下:
<?php
include "connection.php";
?>
<table width="100%" border="1" align="center" cellpadding="2" cellspacing="2">
<tr>
<td>Date</td>
<td>Particulars</td>
<td>Transaction Type</td>
<td>Sub Expense</td>
<td>Expense</td>
<td>Subincome</td>
<td>Income</td>
<td>Cash in Hand</td>
<td>Remarks</td>
</tr>
<?php
$datequery = mysql_query("select date from income order by date asc") or die (mysql_error());
while ($row = mysql_fetch_array($datequery))
{
$currentdate = $row['date'] ;
echo $currentdate."<br>";
$result = mysql_query("SELECT * FROM income WHERE date = '$currentdate' ") or die (mysql_error());
while ($row = mysql_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['particulars']; ?></td>
<td><?php echo $row['trntype']; ?></td>
<td> </td>
<td> </td>
<td><?php $subincome = $row['subincome']; echo $subincome ;?></td>
<td><?php $income = $row['income']; echo $income ?></td>
<td><?php $balance = $balance + $row['subincome'] + $row['income'] - $row['subexpense'] - $row['expense']; ; echo $balance; ?></td>
<td><?php echo $row['remarks']; ?></td>
</tr>
<?php
}
$result = mysql_query("SELECT * FROM expenditure WHERE date = '$currentdate' ") or die (mysql_error());
while ($row = mysql_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['particulars']; ?></td>
<td><?php echo $row['trntype']; ?></td>
<td><?php echo $row['subexpense']; ?></td>
<td><?php echo $row['expense']; ?></td>
<td> </td>
<td> </td>
<td><?php $balance = $balance + $row['subincome'] + $row['income'] - $row['subexpense'] - $row['expense']; echo $balance; ?></td>
<td><?php echo $row['remarks']; ?></td>
</tr>
<?php
}
$date = strtotime($currentdate);
$date = strtotime("+1 day", $date);;
$currentdate = date('Y-m-d', $date);
}
?>
</table>
答案 0 :(得分:1)
您可以使用union all
运算符进行单个查询,并进行相应的排序。在下面的查询中,我添加了一个虚拟列进行排序,因此我可以确保收入中的行始终位于支出行之前:
SELECT *
FROM (SELECT *, 1 AS dummy FROM income
UNION ALL
SELECT *, 2 AS dummy FROM expenditure) t
ORDER BY `date` ASC, dummy ASC
答案 1 :(得分:0)
如果您想要上老学,您可以在一个查询中检索所有收入记录,并将您的所有支出记录排序在另一个查询中,也可以按升序日期排序。将索引保存到每个结果集数组中。在日期更改时逐步增加每个数组索引的递增。您已经完成了merge join
这是union all .. order by
在@ Mureinik的答案中所取得的成就。不过他这样做了;它更好。