Mysql - 创建 View 组合 2 个表但仅通过选择合并而不合并表

标签 mysql sql

在 MySQL 中,我有 2 个表,名为 table_rebatetable_bonus

table_rebate(有 3 个相同的列,2 个不同的列)

a_id     a_value           a_time
 1        1000      2018-05-05 10:25:15
 2        3000      2018-05-05 11:35:15

table_bonus(有 3 个相同的列,3 个不同的列)

b_id     b_value           b_time      
 01        500       2018-05-05 11:20:15
 02        700       2018-05-05 12:30:15

我需要为我的 PHP (CI) View 选择 3 个相同的列到 1 个表中。

Number    from       Values            Time
  1      Rebate       1000      2018-05-05 10:25:15
  2      Bonus         500      2018-05-05 11:20:15
  3      Bonus         700      2018-05-05 11:35:15
  4      Rebate       3000      2018-05-05 12:30:15

我该怎么做?不合并,但需要像合并表一样打印,可以按(a_time & b_time)升序排序。

EXPLAIN select (@rn := @rn + 1) as id, `from`, `values`, `time`
from ((select 'rebate' as `from`, a_value as `values`, a_time as `time`
       from table_rebate
      ) union all
      (select 'bonus' as `from`, b_value, b_time
       from table_bonus
      ) 
     ) br cross join
     (select @rn := 0) params
order by `time`;

enter image description here

最佳答案

你可以使用union all:

select (@rn := @rn + 1) as id, `from`, `values`, `time`
from ((select 'rebate' as `from`, a_value as `values`, a_time as `time`
       from table_rebate
      ) union all
      (select 'bonus' as `from`, b_value, b_time
       from table_bonus
      ) 
     ) br cross join
     (select @rn := 0) params
order by `time`;

请注意,fromvaluestime 都是SQL 中的关键字(即使没有保留)。这使它们成为非常糟糕的列名称。

关于Mysql - 创建 View 组合 2 个表但仅通过选择合并而不合并表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50185263/

相关文章:

java - Spring Jdbc模板+ MySQL = TransientDataAccessResourceException : Invalid Argument Value : Java. io.notSerializationException

MySQL Workbench : "SELECT" is not valid at this position for this server version, 期望 : '(' , WITH 错误

c# - 插入多个值并返回多个值

sql - 克隆一条记录,然后使用它的自动递增 id 进行进一步的操作

mysql - 将时间列从 24 小时格式转换为 12 小时格式时排序不正确

mysql - 在 MySQL 中创建计划事件

mysql - MySQL中VARCHAR(255)的存储大小是多少

php - SQL语法错误,PHP MYSQL

php - 如何使用mysql获取woocommerce订单信息到新页面显示

php - 请提供数据库架构建议