我有2张桌子
deposits
id |userId | amount| Date
1 | 2 | 150 | 2013-11-22 02:57:00
2 | 3 | 230 | 2013-11-25 03:19:00
withdrawals
id |userId | amount| Date
1 | 2 | 150 | 2013-11-23 02:57:00
2 | 3 | 190 | 2013-11-27 02:27:00
我想创建一个视图,以这种格式显示来自两个表的数据 优选地,记录应该按日期字段排序,但这并不重要,因为我可以按日期查询查看视图。
depositsAndWithdrawal
type | id | userId| amount | Date
deposit | 1 | 2 | 150 | 2013-11-22 02:57:00
withdrawal | 1 | 2 | 150 | 2013-11-23 02:57:00
deposit | 2 | 3 | 230 | 2013-11-25 03:19:00
withdrawal | 2 | 3 | 190 | 2013-11-27 02:27:00
这甚至可能吗?或者我是否需要创建一个新表并使用on insert事件向该表添加相关行?
答案 0 :(得分:0)
您正在寻找union all
查询。你可以在MySQL视图中执行此操作:
create view v as
select 'deposit' as which, id, userId, amount, Date
from deposits
union all
select 'withdrawals' as which, id, userId, amount, Date
from withdrawals ;
答案 1 :(得分:0)
以下内容(原谅小错误):
create view depositsAndWithdrawal as
(
select 'deposits' as type, id, userID, amount, date
from deposits
UNION
select 'withdrawls' as type, id, userID, amount, date
from widthdrawls
)
然后您可以使用以下方式查询:
select * from depositsAndWithdrawal order by date;
不幸的是,我不认为您可以拥有视图顺序,因为您需要在视图中使用临时表,例如:
不起作用:
create view depositsAndWithdrawal as
(
select * from
(select 'deposits' as type, id, userID, amount, date
from deposits
UNION
select 'withdrawls' as type, id, userID, amount, date
from widthdrawls) as temp order by date
)
但您可以将问题分成两个视图:
create view depositsAndWithdrawalTemp as
(
select 'deposits' as type, id, userID, amount, date
from deposits
UNION
select 'withdrawls' as type, id, userID, amount, date
from widthdrawls
)
create view depositsAndWithdrawal as
select * from depositsAndWithdrawalTemp order by date;