-->

Mysql query for price comparison

2020-08-05 10:17发布

问题:

I am working on a price comparison program. I have three websites. In my database I have three tables for the webshops. Each tables has a price and a product_id column. I want to list all the product_id-s and see the prices in every webshop. The product id is unique, but not the same in all of the tables, as not all webshop has the same products. I am working with mysql, but I'm very new to databases. What query should I try?

回答1:

I suggest you have a "master" product table, that lists all products, regardless of whether they are sold on all sites, or just one. Then join from that to each of the website pricing tables. Try matching on product name. In its simplest form, the query wold look like:

select
  p.*,
  t1.price as site1_price,
  t2.price as site2_price,
  t3.price as site3_price
from product p
left join website1 t1 on t1.name = p.name
left join website2 t2 on t2.name = p.name
left join website2 t3 on t3.name = p.name;

You might have to try joining on brand and model, ie on t1.brand = p.brand and t1.model = p.model, or some other criteria if name is not unique.

site prices will be null if they don't sell a product.

To quickly populate product, you could run this:

insert into product (name, brand, model, ...)
select name, brand, model, ... from website1
union 
select name, brand, model, ... from website2
union 
select name, brand, model, ... from website3;

FYI, the use of UNION (rather than UNION ALL) makes the output of the union produce only unique rows