MySQL创建视图:仅用SELECT合并两表相同列用于PHP(CI)视图
这事儿很简单,咱们直接用MySQL视图+UNION ALL就能搞定,完美适配你的CodeIgniter展示需求!
解决方案:创建统一视图合并两个表的通用数据
核心思路是把两个表的不同列名统一成一致的字段,加上类型标识区分返利/奖金,用UNION ALL合并结果(比UNION高效,因为不会做去重检查),最后把逻辑封装成视图,后续查询视图就像查普通表一样方便。
1. 创建视图的SQL语句
注意到a_id是整数类型,b_id是字符串类型,为了避免UNION时的类型不一致问题,我们把a_id转成字符串:
CREATE VIEW unified_transactions AS SELECT CAST(a_id AS CHAR) AS record_id, -- 统一记录ID字段,转成字符串和b_id类型匹配 a_value AS amount, -- 统一金额字段 a_time AS create_time, -- 统一时间字段 'Rebate' AS transaction_type -- 标识这是返利类型 FROM table_rebate UNION ALL SELECT b_id AS record_id, b_value AS amount, b_time AS create_time, 'Bonus' AS transaction_type -- 标识这是奖金类型 FROM table_bonus;
如果你的业务里不需要担心ID类型的问题(比如只做展示不做关联),也可以去掉CAST直接用a_id AS record_id。
2. 视图查询结果示例
执行SELECT * FROM unified_transactions;会得到如下格式的数据,完全符合展示需求:
| record_id | amount | create_time | transaction_type |
|---|---|---|---|
| 1 | 1000 | 2018-05-05 10:25:15 | Rebate |
| 2 | 3000 | 2018-05-05 11:35:15 | Rebate |
| 01 | 500 | 2018-05-05 11:20:15 | Bonus |
| 02 | 700 | 2018-05-05 12:30:15 | Bonus |
3. 在CodeIgniter中使用这个视图
控制器代码
在控制器里直接查询视图,和操作普通表完全一样:
public function display_transactions() { // 查询视图获取所有统一后的交易数据 $data['transactions'] = $this->db->get('unified_transactions')->result(); // 加载视图并传递数据 $this->load->view('transaction_list', $data); }
视图代码(transaction_list.php)
在视图里循环展示数据,附带安全处理:
<div class="transaction-table"> <table border="1"> <thead> <tr> <th>记录ID</th> <th>金额</th> <th>创建时间</th> <th>交易类型</th> </tr> </thead> <tbody> <?php foreach ($transactions as $item): ?> <tr> <td><?php echo htmlspecialchars($item->record_id); ?></td> <td><?php echo htmlspecialchars($item->amount); ?></td> <td><?php echo htmlspecialchars($item->create_time); ?></td> <td><?php echo htmlspecialchars($item->transaction_type); ?></td> </tr> <?php endforeach; ?> </tbody> </table> </div>
这里用htmlspecialchars是为了防止XSS攻击,属于常规的安全操作。
内容的提问来源于stack exchange,提问作者user9125729
相关产品推荐
相关产品推荐

