简体   繁体   中英

MYSQL create view that show data from two tables

I have 2 tables

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

I want to create a view that will show data from both tables in this format Preferably the records should be ordered by the date field, though it is not critical since I can Query the view with order by date.

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

Is this even possible? or do I need to create a new table and use the on insert event to add a relevant line to that table?

You are looking for a union all query. And you can do this in a MySQL view:

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 ;

Something along the lines of the following (excuse small errors):

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
)

You can then query this using:

select * from  depositsAndWithdrawal order by date;

Unfortunately, I don't think you can have the view order this as you would need to use a temporary table within the view eg:

Doesn't work:

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
    )

But you could split the problem into two views:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM