如何从两个表中获取日期报告?
信用表:
------------------------
Date | Amount
------------------------
20/10/2014 | 1200
------------------------
10/10/2014 | 3200
------------------------
05/10/2014 | 1300
------------------------
借记卡表:
------------------------
Date | Amount
------------------------
20/10/2014 | 2200
------------------------
15/10/2014 | 5200
------------------------
02/10/2014 | 1800
------------------------
输出应为:
Date Cr Dr
------------------------------
20/10/2014 1200 2200
15/10/2014 0 5200
10/10/2014 3200 0
05/10/2014 1300 0
02/10/2014 0 1800
我尝试了以下方法:
$date[] = { '20/10/2014','19/10/2014',........Last date };
$i=0;
while ($<sizeof($date))
{
$credit = mysql_fetch_assoc(mysql_query("select * from credit where date='".$date[$i]."'"));
$debit = mysql_fetch_assoc(mysql_query("select * from debit where date='".$date[$i]."'"));
echo $credit["amount"]. $debit["amount"];
}
我在date
和from
日期之间的所有日期都收集了to
。
我知道这是一个糟糕的方法,它减慢了页面的执行速度,所以我怎么能以更聪明的方式解决这个问题?
提前谢谢。
答案 0 :(得分:2)
SELECT * FROM (SELECT a.`Date`,
IFNULL(a.Amount, 0) AS Cr,
IFNULL(b.Amount, 0) AS Dr
FROM Credit a
LEFT JOIN Debit b
ON a.`Date` = b.`Date`
UNION
SELECT b.`date`,
IFNULL(a.Amount, 0) AS Cr,
IFNULL(b.Amount, 0) AS Dr
FROM Credit a
RIGHT JOIN Debit b
ON a.`date` = b.`date`)t
ORDER BY t.`Date` DESC;
答案 1 :(得分:0)
使用以下查询,因为mysql中没有外连接使用左右连接
SELECT date, IFNULL(c.amount, 0) AS credit, IFNULL(d.amount, 0) AS debit
FROM credit c LEFT JOIN debit d
ON c.date = d.date
ORDER BY date DESC
UNION
SELECT date, IFNULL(c.amount, 0) AS credit, IFNULL(d.amount, 0) AS debit
FROM credit c RIGHT JOIN debit d
ON c.date = d.date
ORDER BY date DESC
PHP代码就像这样
$query = 'SELECT date, IFNULL(c.amount, 0) AS credit, IFNULL(d.amount, 0) AS credit
FROM credit c LEFT JOIN debit d
ON c.date = d.date
ORDER BY date DESC
UNION
SELECT date, IFNULL(c.amount, 0) AS credit, IFNULL(d.amount, 0) AS credit
FROM credit c RIGHT JOIN debit d
ON c.date = d.date
ORDER BY date DESC';
$con = mysqli_connect( ) //Connection string;
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{echo '<tr>
<td>'.$row["date"].'</td>
<td>'.$row["credit"].'</td>
<td>'.$row["debit"].'</td>
</tr>';
}
答案 2 :(得分:0)
我会使用以下查询,在两个表之间使用左外连接并联内部连接,不包括内部连接匹配记录,并将左表值默认为0.如果信用卡中没有重复日期。借记表可以从sql语句中删除sum方法。
select c.date_, ifnull(sum(c.amount),0) cr, ifnull(sum(d.amount),0) db from credit c left outer join debit d on c.date_ = d.date_
group by c.date_
union all
select d.date_, 0 cr, ifnull(sum(d.amount),0) db from credit c right outer join debit d on c.date_ = d.date_ where c.date_ is null
group by d.date_
order by date_ desc
在这里,您可以使用sql fiddle链接作为参考