what database model to use?
i need a database with the following sheme:
Product | Discounter | Price
----------------------------------------------开发者_JAVA百科-----------
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"?
Thanks in advance, unknown
Use two tables. Your tables could look like the following (in pseudo 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:
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. 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.
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
精彩评论