简体   繁体   English

使用哪种数据库模型?

[英]what database model to use?

i need a database with the following sheme: 我需要具有以下sheme的数据库:

Product | Discounter | Price
---------------------------------------------------------
Onion   |   a   |   99.99
  | b  | 1.07
  | c | 750.00
Garlic  |   a   |   0.39
  | b | 17.56
  | c | 3.59

I want to use MySQL, but how can i expand the "Product" cell over each row in "Discounter"? 我想使用MySQL,但是如何在“折扣”中的每一行上展开“产品”单元格?

Thanks in advance, unknown 在此先感谢,未知

Use two tables. 使用两个表。 Your tables could look like the following (in pseudo DDL) 您的表可能如下所示(使用伪DDL)

Product
   product_id int,
   product_name varchar(20),
   constraint pk_product primary key (product_id)

ProductDiscounter
   product_id int,
   discounter char(1),
   price decimal,
   constraint pk_product_discounter primary key (product_id, discounter),
   constraint fk_product_discounter foreign key (product_id) references (Product.product_id)

To select the different prices for a product with, say, id 1 you could execute the following select statement: 要为编号为1的产品选择不同的价格,您可以执行以下选择语句:

select p.product_name, pd.discounter, pd.price 
from Product p, ProductDiscounter pd
where p.product_id = pd.product_id 
and p.product_id = 1

You cannot have a cell in one column span multiple rows. 一列中的单元格不能跨越多行。

Klaus's answer is very general (and supports hanging a variety of other data off product IDs), so I'd go with that if you have any real complexity to your problem. Klaus的回答非常笼统(并支持在产品ID上悬挂各种其他数据),因此,如果您对问题有任何真正的复杂性,我将拒绝。 However, if the case is as simple as described in your question, you can just put the Product name in each row. 但是,如果情况如问题所描述的那样简单,则只需将产品名称放在每一行中。 A SELECT * WHERE Product == whatever will work just fine on that sort of table. SELECT * WHERE Product ==在这种表上可以正常工作的任何东西。

I'd also recommend as very useful a group function after your tables are structured / normalized in the manner that Klaus has designated. 在按照克劳斯指定的方式对表进行结构化/规范化之后,我还建议将组函数作为非常有用的功能。 What's nice about this is you can actually have the db calculate stats like an average price, amongst discounters, for each product. 这样做的好处是,您实际上可以让数据库计算各种产品的统计信息,例如折扣中的平均价格。 I'll also point out that you can sort the final result (even after grouping) by the product name to keep everything interface-friendly when displayed. 我还将指出,您可以按产品名称对最终结果(即使在分组后)进行排序,以确保显示时界面友好。

SELECT p.product_name, pd.discounter, Avg(pd.price) as `Average Discounter Price`
FROM Product p
LEFT JOIN ProductDiscounter pd ON p.product_id = pd.product_id
GROUP BY p.product_id
ORDER BY p.product_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM