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

时间:2011-02-21 23:09:58

标签: php mysql database

我有两个表,第一个表有产品,第二个表有价格。价格表可能每个产品有多个价格,但我只想显示最低价格。但是我不断收到所有的价格,而我却无法弄清楚如何去做。

这是我在查询中返回的内容:

SELECT * FROM products AS pr JOIN prices AS p ON pr.id = p.product_id WHERE pr.live = 1 AND 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

但我在追求:

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

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

按产品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

更新:像MIN( CAST( SUBSTR( price, 2 ) AS DECIMAL )之类的内容可以帮助摆脱£字符并转换为数字以便在价格上进行正确的汇总

答案 1 :(得分:0)

明智地应用分组和aggregate functions将达到预期的效果。

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

但是,如果price列是文本类型,它可能不会使用您想要的collation,并且(例如)'£100'将被视为低于'£90'。