2014-01-16 62 views
0

顯示數據我有2個表MYSQL創建視圖,從兩個表

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 

這甚至有可能嗎?或者我是否需要創建一個新表並使用插入事件將相關行添加到該表中?

回答

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 ; 
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;