简体   繁体   中英

How to create View of three tables with relations in MySQL

I have three tables, the first one about products, the second about authors and the third table illustrates which product is related to which author. The reason that I have three tables is that a product can have more than one author.

product : 
id  |   name   |   price

user :
id   |   name   

user_product :
product_id   |   user_id

now I want to create a view which includes id, name and price from the product table and "name" from user table, so that if there are more than one authors, their names are separated with a comma.

view_product :
id   |   product_id   |   product_name   |   product_price   |   user_name

I would appreciate it very much if anyone can help me with writing this query.

One option uses a correlated subquery and string aggregation function group_concat() :

create view myview as
select p.id as product_id, p.name as product_name, p.price as product_price,
    (
        select group_concat(u.name)
        from user_product up
        inner join user u on u.id = up.user_id
        where up.product_id = p.id
    ) as user_names
from product p

You can also join and aggregate:

create view myview as
select p.id as product_id, p.name as product_name, p.price as product_price,
    group_concat(u.name) as user_names
from product p
left join user_product up on up.product_id = p.id
left join user u on u.id = up.user_id
group by p.id

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