Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

39 产品销售分析 I #48

Open
astak16 opened this issue Feb 8, 2022 · 0 comments
Open

39 产品销售分析 I #48

astak16 opened this issue Feb 8, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Feb 8, 2022

题目

写一条SQL 查询语句获取 sales 表中所有产品对应的 产品名称 product_name 以及该产品的所有 售卖年份 year 和 价格 price 。

  • (sale_id, year) 是销售表 sales 的主键
  • sales 表中的 product_id 是关联到产品 product 的外键
  • product 表中的 product_id 是主键
CREATE TABLE sales (
	sale_id INT,
	product_id INT,
	year INT,
	quantity INT,
	price INT 
);
INSERT INTO sales ( sale_id, product_id, year, quantity, price ) VALUES
( '1', '100', '2008', '10', '5000' ),
( '2', '100', '2009', '12', '5000' ),
( '7', '200', '2011', '15', '9000' );
	
CREATE TABLE product ( 
	product_id INT, 
	product_name VARCHAR ( 10 ) 
);
INSERT INTO product ( product_id, product_name ) VALUES
( '100', 'Nokia' ),
( '200', 'Apple' ),
( '300', 'Samsung' );

分析:

  1. 两张表做关联,往往是一张表的外键关联另一张表的主键
  2. 这边是 sales 表中的外键 product_idproduct 表中的主键 product_id 做关联

所以方法一和方法二都是使用这种方法的不同形式。

SQL:方法一

select product_name, year, price from sales join product using(product_id)

解析

使用 join 方法连接两张表,连接条件是 product_id

SQL:方法二

select 
	product_name,
	year, 
	price 
from sales, product where sales.product_id = product.product_id

解析

两表查询,通过 where 连接两张表之间的 product_id

@astak16 astak16 added the 简单 label Feb 8, 2022
@astak16 astak16 changed the title 39 产品销售分析 39 产品销售分析 I Feb 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant