简体   繁体   English

如何联接两个数据库表并从联接表中返回最低价格

[英]How Can I Join Two DB Tables and Return Lowest Price From Joined Table

I have two tables, the first table has the product and the second table the prices. 我有两个表,第一个表包含产品,第二个表包含价格。 The price table could have more than one price per product but I only want to display the lowest. 价格表每个产品可能有多个价格,但我只想显示最低价格。 But I keep getting all the prices returned and I'm having trouble figuring out how to do it. 但是我一直都在退还所有价格,因此我很难弄清楚该怎么做。

this is what I get returned in my query: 这是我在查询中返回的内容:

SELECT * FROM products AS pr JOIN prices AS p ON pr.id = p.product_id WHERE pr.live = 1 AND p.live = 1 products选择*从现在开始,以联合prices作为开始,当pr.id = p.product_id时,pr.live = 1和p.live = 1

id product1 name description £100
id product1 name description £300
id product1 name description £200
id product2 name description £50
id product2 name description £80
id product2 name description £60
id product3 name description £222
id product3 name description £234
id product3 name description £235

but I'm after: 但我追求:

id product1 name description £100
id product2 name description £50
id product3 name description £222

Any help would be appreciated 任何帮助,将不胜感激

Group by product id an aggregate min on price 按产品ID分组,总计价格最小值

SELECT pr.*, p.m_price
FROM `products` AS pr 
  INNER JOIN (
    SELECT product_id, min(price) AS m_price
    FROM `prices`
    WHERE live = 1
    GROUP BY product_id
  ) AS p 
    ON pr.id = p.product_id 
WHERE pr.live = 1

update: something like this MIN( CAST( SUBSTR( price, 2 ) AS DECIMAL ) could help to get rid of the £ char and convert to number for correct aggregation on price 更新:像这样的MIN( CAST( SUBSTR( price, 2 ) AS DECIMAL )可能有助于摆脱£ char并转换为数字以正确组合价格

Judicious application of grouping and aggregate functions will achieve the desired results. 明智地应用分组功能聚合功能将获得预期的结果。

SELECT pr.id, pr.title, pr.name, pr.description, min(p.price)
  FROM products AS pr 
    JOIN prices AS p ON pr.id = p.product_id 
  WHERE pr.live = 1 AND p.live = 1
  GROUP BY pr.id

However, if the price column is a text type, it probably won't use the collation you want, and (eg) '£100' will be considered less than '£90'. 但是,如果价格列是文本类型,则可能不会使用您想要的排序规则 ,并且(例如)“£100”将被认为小于“£90”。

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

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