mysql - 4个表的内连接

标签 mysql sql inner-join

表格

生产

enter image description here

类别

enter image description here

订单

enter image description here

订单详情

enter image description here

我已将 SalesView 制作如下

create view salesView as select o.oID, p.name as product, od.sell_price as price, od.qty as quantity, o.order_date
    from orderDetails od inner join
    orders o on o.oID = od.oID,
    production p where = p.ID = od.pID;

由于 od(表 OrderDetails 的实例)不包含对类别表的引用。如何在 SalesView 中添加“类别”列?

现在,

select * from SalesView;

enter image description here

我想在其中添加“类别”列。

我已经尝试过了...

create view salesView as select o.oID, p.name as product, c.name as category, od.sell_price as price, od.qty as quantity, o.order_date
    from orderDetails od inner join
    orders o on o.oID = od.oID,
    production p where = p.ID = od.pID,
    category c where c.ID = ???

最佳答案

不要混合符号/标准。要添加类别,只需将类别内部连接到您的生产表即可。这假设所有作品都有一个类别;否则您可能需要左(外)连接。

create view salesView as 
SELECT o.oID
     , p.name as product
     , c.name as category
     , od.sell_price as price
     , od.qty as quantity
     , o.order_date
     , c.name
FROM orderDetails od 
INNER JOIN orders o 
   on o.oID = od.oID
INNER JOIN Production p 
   on p.ID = od.pID
INNER JOIN Category c
   on c.ID = P.catID
WHERE...

不要这样做:

create view salesView as select o.oID, p.name as product, od.sell_price as price, od.qty as quantity, o.order_date
    from orderDetails od inner join --<See the inner join
    orders o on o.oID = od.oID, --<See the ,  (don't mix standards!)
    production p where = p.ID = od.pID;

注意标准的差异:https://gerardnico.com/data/type/relation/sql/join_default_ansi92_comparison

关于mysql - 4个表的内连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58342333/

相关文章:

mysql - SQL查询根据ID聚合记录

c# - 将大量记录插入 SQL Server 数据库的最快方法是什么?

php - MySQL加入3个级联表

MySQL 在子子查询中用连接替换 IN 和 EXISTS

mysql - pandas 查询分组内的分组

php - mysqli 每次只工作 else 条件但不工作 if 条件

mysql - 用于获取 MySql 表行的事件处理程序

连接 CTE 时 SQL Server 语法错误

sql - 是否存在关于 ActiveRecord 关系的困惑?方法,尤其是限制和偏移

php - MySQL关系查询