查找每个客户的所有销售情况

时间:2015-12-10 23:04:32

标签: mysql sql select mysql-workbench

我正在尝试列出所有与客户ID链接的销售,所以我希望看到

sale ID    customerID    customerfirstname    customerlastname 
1          1             J                    Bloggs
2          2             G                    Green
3          1             J                    Bloggs

这就是我所拥有的一切,并且它不太正确......

SELECT  sale.sale_id
        customer.customer_id ,
        customer.customer_first_name , 
        customer.customer_last_name , 
FROM mydb.customer , mydb.sale
WHERE sale.sale_id = customer_id

这是我的结构

CREATE TABLE `sale` (
  `sale_id` int(11) NOT NULL,
  `sale_items` int(3) NOT NULL,
  `sale_paid` tinyint(1) DEFAULT NULL,
  `customer_customer_id` int(11) NOT NULL,
  PRIMARY KEY (`sale_id`,`customer_customer_id`),
  KEY `fk_sale_customer1_idx` (`customer_customer_id`),
  CONSTRAINT `fk_sale_customer1` FOREIGN KEY (`customer_customer_id`) REFERENCES `customer` (`customer_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `customer` (
  `customer_id` int(11) NOT NULL,
  `customer_first_name` varchar(45) DEFAULT NULL,
  `customer_last_name` varchar(45) DEFAULT NULL,
  `customer_address1` varchar(45) DEFAULT NULL,
  `customer_address2` varchar(45) DEFAULT NULL,
  `customer_address3` varchar(45) DEFAULT NULL,
  `customer_post_code` varchar(45) DEFAULT NULL,
  `customer_debit` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4 个答案:

答案 0 :(得分:2)

您需要使用JOIN来连接表格。 通过查看您的表,看起来customer_customer_idsale表中与客户ID匹配的列:

SELECT  sale.sale_id
        customer.customer_id ,
        customer.customer_first_name , 
        customer.customer_last_name 
FROM customer INNER JOIN sale on 
sale.customer_customer_id = customer.customer_id

答案 1 :(得分:2)

您应该在客户ID上加入客户ID,而不是在销售ID上。

SELECT  sale.sale_id,
        customer.customer_id ,
        customer.customer_first_name , 
        customer.customer_last_name 
FROM mydb.customer INNER JOIN mydb.sale ON sale.customer_customer_id = customer.customer_id

答案 2 :(得分:1)

您正在加入错误的字段 - 两个表都有一个引用客户ID的列,您应该使用该列。此外,在选择列表中的最后一项之后有一个冗余逗号,并且在第一项之后缺少一个逗号:

SELECT  sale.sale_id,
        customer.customer_id,
        customer.customer_first_name, 
        customer.customer_last_name
FROM    customer, sale
WHERE   sale.customer_customer_id = customer.customer_id

但请注意,使用隐式连接(即from子句中有多个表)已弃用且不鼓励,您应该使用显式连接:< / p>

SELECT  sale.sale_id,
        customer.customer_id,
        customer.customer_first_name, 
        customer.customer_last_name
FROM    customer
JOIN    sale ON sale.customer_customer_id = customer.customer_id

答案 3 :(得分:1)

对于你的结构,它应该是这样的:

SELECT  s.sale_id
        s.customer_id ,
        c.customer_first_name , 
        c.customer_last_name , 
FROM 
  mydb.customer c
INNER JOIN
  mydb.sale s
ON 
  s.customer_id = c.customer_id