从具有多个关系的其他表中获取min()

时间:2016-07-08 11:50:02

标签: php mysql inner-join min

我正在尝试为products.desc创建全文搜索。作为我想要的回应

  • 产品:id,desc
  • 价格:与...相关的最低价格行 products.id
  • 供应商:id,提供该价格的供应商名称。

我正在使用

public string Name
{
 get
  {
   return MyEntity.Name;
  }
 set
  {
   ...
  }
}

这是返回正确(最低)价格,虽然所有其他价格的价值。* - 行未确定/错误。由于GROUP BY prices.product_id获取具有最低ID的列/行。

SELECT products.id, MIN(prices.price) as prices_price, prices.id as prices_id, products.desc, products.product_number, prices.supplier_id, suppliers.name FROM products
 INNER JOIN prices
 ON prices.product_id = products.id
 INNER JOIN suppliers
 ON prices.supplier_id = suppliers.id
 WHERE 
 MATCH (products.desc) AGAINST ('test*' IN BOOLEAN MODE)
 GROUP BY prices.product_id

1 个答案:

答案 0 :(得分:2)

您必须通过加入子查询来获得最低价格,该子查询将价格分组并返回最低价格和相应的product_id。

然后再次加入价格表以获取最低价格的数据集。

然后使用最低价格数据集的supplier_id加入供应商。

Fiddle

SELECT
    products.id,
    lowestPrice.price,
    prices.id AS prices_id,
    products.desc,
    prices.supplier_id,
    suppliers.name
FROM
    products
INNER JOIN (
    SELECT
        prices.price,
        prices.product_id
    FROM
        prices
    GROUP BY
        product_id
    HAVING
        MIN(prices.price)
) AS lowestPrice ON lowestPrice.product_id = products.id
INNER JOIN prices ON prices.price = lowestPrice.price AND prices.product_id = lowestPrice.product_id
INNER JOIN suppliers ON prices.supplier_id = suppliers.id
WHERE 
 MATCH (products.desc) AGAINST ('test*' IN BOOLEAN MODE)