简体   繁体   中英

Fetch rows and columns from two tables

I have two tables in my SQLite database. cash and bank both the tables contain the following attributes (id, person_id, date, remarks, type, amount, balance) I want to fetch all the transactions stored in both the tables which has to be sorted by date, for that, I used UNION but I also want to get 2 separate columns for cash balance and bank balance if the record is coming from cash table then only the cash balance should change and bank balance should remain same. Here is my code

$sql = "SELECT *, 'cash' AS mop 
        FROM cash 
        UNION ALL SELECT *, 'bank' AS mop 
                  FROM bank 
                  ORDER BY date DESC";

        $result = $db->query($sql); ?>
        <tr class="tab-head">
            <td>Date & Time</td>
            <td>Narration</td>
            <td>Mode</td>
            <td>Debit</td>
            <td>Credit</td>
            <td>Cash Balance</td>
            <td>Bank Balance</td>
        </tr> <?php
        if(numr($result)>0){
            while ($row=$result->fetchArray(SQLITE3_ASSOC)) { 
                $date = date("d/m/Y h:i:s", strtotime($row['date']));
                $remarks = $row['remarks'];
                $type = $row['type'];
                $amount = $row['amount'];
                $balance = $row['balance'];
                $mop = $row['mop'];
                $type == "in" ? ($credit = $amount AND $debit = "-") : ($debit = $amount AND $credit = "-"); 
                $mop == "cash" ? ($cbal = $balance AND $bbal = "-") : ($bbal = $balance AND $cbal = "-"); ?>
                <tr>
                    <td><?php echo $date; ?></td>
                    <td><?php echo $remarks; ?></td>
                    <td><?php echo $mop; ?></td>
                    <td><?php echo $debit; ?></td>
                    <td><?php echo $credit; ?></td>
                    <td><?php echo $cbal; ?></td>
                    <td><?php echo $bbal; ?></td>
                </tr> <?php
            }
        }

这就是我从上面的代码中得到的 As You can see in the Output if the source table is cash it is showing the modified cash balnce and leaving the bank balance blank and vice versa. What I want is I want to display the unchanged balance in the place of - Can anyone please help me with any sql query or PHP code, both are accepted but I will prefer a proper sql query. Please Help

Specify the columns that you want before doing the union all :

select id, person_id, date, remarks, type, amount,
       balance as cash_balance, 0 as bank_balance
from cash
union all
select id, person_id, date, remarks, type, amount,
       balance as cash_balance, balance as bank_balance
from cash
order by date desc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM