【问题标题】:Is union all going to work on this?工会都会为此努力吗?
【发布时间】:2018-05-18 14:21:09
【问题描述】:

我有两张表,收入和支出,尝试使用 union all,但问题是支出列显示在收入中,因此影响余额。知道我哪里出错了吗?

<?php
include "connection.php" ;

$result = mysql_query("select date, particulars, trntype, subincome, income, remarks,1 AS dummy from income UNION ALL select date, particulars, trntype, subexpense, expense,remarks, 2 AS dummy from expenditure ORDER BY `date` ASC, dummy ASC");
echo "<table border='1'>
<tr>
<th>Date</th>
<th>Particulars</th>
<th>Transaction Type</th>
<th>Sub Expense</th>
<th>Expense</th>
<th>Sub Income</th>
<th>Income</th>
<th>Cash In Hand</th>
<th>Remarks</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
   echo "<tr>";
  echo "<td>" . $row['date'] . "</td>";
  echo "<td>" . $row['particulars'] . "</td>";
  echo "<td>" . $row['trntype'] . "</td>";
  echo "<td>" . $row['subexpense'] . "</td>";
  echo "<td>" . $row['expense'] . "</td>";
  echo "<td>" . $row['subincome'] . "</td>";
  echo "<td>" . $row['income'] . "</td>";
  $cashinhand = $cashinhand + $row['income'] + $row['income'] - $row['subexpense'] - $row['expense'] ;
    echo "<td>" . $cashinhand . "</td>";
      echo "<td>" . $row['remarks'] . "</td>";
  echo "</tr>";
  }
  echo "</table>";

?>

这里,在 Sub Expense 和 Expense 列中,不显示 subexpense 和费用,而是将它们打印到 Sub Income 和 Income 列中。自然,余额是增加而不是减少。

【问题讨论】:

    标签: mysql sql html-table


    【解决方案1】:

    在您的查询中发生的情况是您将费用和收入混合在同一列中(第 3 列和第 4 列)。

    尝试在每个查询不需要的列上添加null

    SELECT date,
           particulars,
           trntype,
           NULL as subexpense,
           NULL as expense,
           subincome,
           income,
           remarks,
           1 AS dummy
    FROM   income
    UNION ALL
    SELECT date,
           particulars,
           trntype,
           subexpense,
           expense,
           NULL as subincome,
           NULL as income,
           remarks,
           2 AS dummy
    FROM   expenditure
    ORDER  BY `date` ASC,
              dummy ASC  
    

    这样,每个子查询的格式与预期的 HTML 输出相同,每个值类型都有不同的列。

    【讨论】:

      【解决方案2】:

      您必须在每个查询中添加一个伪列以保持联合的分隔。

      select date, particulars, trntype, subincome, income, 
        null as expence, remarks,1 AS dummy 
      from income 
      UNION ALL 
      select date, particulars, trntype, subexpense, null as income, 
          expense, remarks, 2 AS dummy from expenditure ORDER BY `date` ASC, dummy ASC
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多