如何在SQL中从多个表中获取数据

时间:2019-02-18 12:44:16

标签: mysql sql

create table customers
    (
    custID int(11) primary key, 
    customerName varchar(50),
    phone varchar(50),
    address varchar(50),
    state varchar(50),
    postalCode varchar(15),
    country varchar(50),
    creditLimit Decimal(10,2)
    );

create table product
(
    productID varchar(15) primary key,
    productName varchar(70),
    productVendor varchar(50),
    productDescription text,
    qtyInStock smallint(6),
    price Decimal(10,2)
);

create table orders
(
    orderNumber int(11) primary key,
    orderDate date,
    requiredDate date,
    shippedDate date,
    status varchar(15),
    comments text,
    custID int(11),
    salesID int(11),
    foreign key(custID) references customers(custID),
    foreign key(salesID) references salespersonnel(employeeID)
);

这是三个表,我想获取一个特定客户的所有订单及其总花费。

我在订单表和付款表中有两个条目

付款表: enter image description here

订单表: enter image description here

我正在执行此查询

select count(p.orderNumber) as 'Total Orders', sum(amount) as 'Amount Spent'
from orders p,
     payments q
where p.custid = q.custid
  and q.custid = 1;

此查询产生双重结果 这意味着必须总共返回2200作为花费的总金额,但是我得到4400 总共有2个订单是由客户下达的,但我要得到4个。请帮助

2 个答案:

答案 0 :(得分:0)

您需要先汇总 加入。否则,您将获得笛卡尔积(以及您看到的错误结果):

select o.custid, o.Total_Orders, p.Amount_Spent
from (select o.cust_id, count(*) as total_orders
      from orders o
      group by o.custid
     ) o left join 
     (select p.cust_id, sum(amount) as amount_spent
      from payments p
      group by p.cust_id
     ) p
     on p.custid = o.custid ;

您可以添加WHERE子句以过滤结果。您可以在外部查询或子查询中执行此操作。从性能角度来看,后者更好。

注意:

  • 从不FROM子句中使用逗号。 始终使用正确的,明确的,标准 JOIN语法。
  • 使用有意义的表别名。用p代替orders的{​​{1}}真是令人困惑。
  • 在列别名中仅使用字母,数字和下划线,因此不必转义。

答案 1 :(得分:0)

您需要联接ordernumber列上的2个表:

select 
  count(o.orderNumber) as 'Total Orders', 
  sum(p.amount) as 'Amount Spent'
from orders o inner join payment p
on p.ordernumber = o.ordernumber
where o.custid = 1

请参见demo 如果您想为每个客户获取这些金额:

select
  o.custid,
  count(o.orderNumber) as 'Total Orders', 
  sum(p.amount) as 'Amount Spent'
from orders o inner join payment p
on p.ordernumber = o.ordernumber
group by o.custid