跨表正确的SQL乘法

跨表正确的SQL乘法

我在尽头。我正在上一堂课学习SQL。我试图使类似于工作的东西,但无济于事。有人可以看看吗。

请记住,我是新手。我正在尝试获取使小计等于qty列的总和乘以甜甜圈表中的donutPrice列的总和的代码。除了连接,我找不到很多东西,如果这样做,就无法将连接用作值。

最终目标是使其自动化。

CREATE TABLE donut
(
  donutID int(50) not null auto_increment primary key,
  donutName varchar(50) not null,
  donutDesc varchar(200),
  donutPrice dec(8,2)
);
CREATE TABLE customer
(
  customerID int(50) not null auto_increment primary key,
  fname char(50) not null,
  lname char(50) not null,
  address varchar(50) not null,
  apartment varchar(10),
  city char(50) not null,
  state char(2) not null,
  zip dec(5) not null,
  homeph varchar(10),
  mobileph varchar(10),
  otherph varchar(10)
);
CREATE TABLE invoice
(
  orderID int(50) not null auto_increment primary key,
  notes varchar(50) not null,
  orderdate date not null,
  customerID int(50) not null default 1,
  foreign key (customerID) references customer(customerID)
);
CREATE TABLE invoice_line_item
(
  donutID int(50) not null,
  orderID int(50) not null,
  qty dec not null,
  subtotal dec(10,2),
  subtotal= sum('qty'*'donutPrice') FROM (invoice_line_item, donut),
  primary key (donutID, orderID),
  foreign key(donutID) references donut(donutID),
  foreign key(orderID) references invoice(orderID)
);

ALTER TABLE donut AUTO_INCREMENT=1;
ALTER TABLE customer AUTO_INCREMENT=1001;
ALTER TABLE invoice AUTO_INCREMENT=500;

最佳答案

我想你想要一个看起来像这样的结果:

OrderID  subtotal
  1       12.50
  2       15.00
          27.50


您可以通过以下查询获得该信息:

 SELECT invoice.orderID, SUM(invoice_line_item.qty * donut.donutPrice) subtotal
   FROM invoice
   JOIN invoice_line_item ON invoice.orderID = invoice_line_item.orderID
   JOIN donut ON invoice_line_item.donutID = donut.donutID
  GROUP BY invoice.orderID WITH ROLLUP


您是否在课堂上讨论过实体关系数据?您的实体是发票,invoice_line_item和甜甜圈(以及其他表格)。它们之间的关系出现在ON操作的JOIN子句中。

从查询开始,然后使其开始工作。然后,您可以创建一个视图...,它只不过是封装的查询而已。

关于mysql - 跨表正确的SQL乘法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52305165/

10-11 19:37