MySQL create view joining two tables
Asked Answered
P

3

19

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
Poulos answered 10/9, 2012 at 12:47 Comment(3)
I couldn't add images to question, so they are here: i.sstatic.net/YCfAO.png i.sstatic.net/7AUhc.png i.sstatic.net/8W06W.png i.sstatic.net/forWs.pngPoulos
What is the problem? The query part (ie how to fetch that data from those tables), or how to create a view in MySQL?Asgard
@th0th check my answer below. hope it helps.Likeness
L
26

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
Likeness answered 10/9, 2012 at 12:53 Comment(2)
Changed FROM gift a to FROM gifts a, thought there was a typo. And I get error: #1054 - Unknown column 'b.users' in 'on clause'Poulos
@th0th it's really a typo, it should be a.user_from = b.id and a.user_from = c.idLikeness
F
2

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.

Fair answered 6/6, 2019 at 15:9 Comment(0)
C
0

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

Chromophore answered 11/3, 2022 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.