如何创建具有 MySQL 中关系的三个表的视图

How to create View of three tables with relations in MySQL

我有三个 table,第一个关于产品,第二个关于作者,第三个 table 说明哪个产品与哪个作者相关。我有三个 table 的原因是一个产品可以有多个作者。

product : 
id  |   name   |   price

user :
id   |   name   

user_product :
product_id   |   user_id

现在我想创建一个视图,其中包含产品 table 的 ID、名称和价格以及用户 table 的“名称”,这样如果有多个作者,他们的名称以逗号分隔。

view_product :
id   |   product_id   |   product_name   |   product_price   |   user_name

如果有人能帮我写这个查询,我将不胜感激。

一个选项使用相关子查询和字符串聚合函数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

您还可以加入聚合:

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