Gokhan Sari
Gokhan Sari

Reputation: 7944

MySQL create view joining two tables

How can I create a view that merges different columns with a different table? I have three tables for example: users, items and gifts (in this example it's a system that a user can give a gift to another user)

users table has information about users, items table has information about items and gifts table shows which user sent what gift to which user.

What I want is to create a view like following:

user_from | user_to | gift_name  | gift_price
sally     | john    | Teddy Bear | 10

Upvotes: 19

Views: 77629

Answers (3)

Nouru Muneza
Nouru Muneza

Reputation: 77

I believe were looking for data blending. So basically having google data studio do a JOIN statement on ids from 2 data sets

Upvotes: 0

Dipanshu Mahla
Dipanshu Mahla

Reputation: 152

You can create a view with two tables like:

 CREATE VIEW giftList AS
 SELECT users.user_from,users.user_to,gifts.gift_name,gifts.gift_price FROM users,gifts
 WHERE users.user_id = gifts.user_id;

The where clause is to make sure the output does not repeat.

Upvotes: 2

John Woo
John Woo

Reputation: 263723

You must join the three tables first. Example

CREATE VIEW GiftsList
AS
SELECT  b.name user_from,
        c.name user_to,
        d.name gift_name,
        d.price gift_price
FROM    gift a
        INNER JOIN users b
            ON a.user_from = b.id
        INNER JOIN users c
            ON a.user_from = c.id
        INNER JOIN items d
            ON a.item = d.id

Upvotes: 26

Related Questions