Mysql-创建视图合并了2个表,但仅通过select合并,不合并表
在MySQL中,我有两个表,分别是Mysql-创建视图合并了2个表,但仅通过select合并,不合并表,mysql,sql,Mysql,Sql,在MySQL中,我有两个表,分别是table\u retrieve和table\u bonus 表\u折扣(有3列相同,2列不同) 表\u奖金(有3个相同的列,3个不同的列) 我需要在PHP(CI)视图中选择3个相同的列作为1个表 我该怎么做?它不需要合并,但需要像合并表一样打印,并且可以按(a_时间和b_时间)升序排序 EXPLAIN select (@rn := @rn + 1) as id, `from`, `values`, `time` from ((select 'rebate' a
table\u retrieve
和table\u bonus
表\u折扣
(有3列相同,2列不同)
表\u奖金
(有3个相同的列,3个不同的列)
我需要在PHP(CI)视图中选择3个相同的列作为1个表
我该怎么做?它不需要合并,但需要像合并表一样打印,并且可以按(a_时间和b_时间)升序排序
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`;
您可以使用
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`;
请注意,
from
、值
和时间
都是SQL中的关键字(即使没有保留)。这使得列的名称非常糟糕。我有一个相同的问题,关于表\u奖金
我应该将b\u值声明为“值”
,将b\u时间声明为“时间”
?对不起,什么是@rn
?谢谢戈登。因为我需要加入4个表,所以@rn
是否适用于4个表?@Cendana。对您可能需要使用另一个子查询和order by
来获得正确的排序。非常感谢gordon,我将尝试将其合并。选择useunion all
是否会导致explain all NULL?
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
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`;
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`;