选择连接表中的最小值

时间:2011-10-11 11:23:08

标签: mysql

对于那些product,基本上我有model和几个product s。每个model都有price

这就是我打算做的事情:

product标记为精选,然后将其设为titledescription,第1张图片的thumbnailprice最便宜的model

这是我目前的查询:

SELECT
  product.title,
  product.url_name,
  product.description,
  price.price,
  image.thumbnail
FROM
  mps_contents AS product
  LEFT OUTER JOIN
    mps_contents AS image 
    ON
      image.page_id = product.content_id AND
      image.display_order = '1' AND
      image.resource_type = 'image'
  LEFT OUTER JOIN
    mps_contents AS model 
    ON
      product.content_id = model.page_id
  INNER JOIN
    mps_product_info AS price
    ON
      model.content_id = price.content_id
WHERE
  product.active = '1' AND
  product.resource_type = 'product' AND
  product.featured = '1'
ORDER BY RAND( )
LIMIT 3

您可能会看到我的查询无法进行price排序,我希望有人可以帮助我。我遇到的另一个问题是,如果model有多个product s。我的目的是为每个price设置1 model时,我最终得到一个product来自单个price的{​​{1}} s的集合

我知道product的问题,但我会忽略它,因为我不认为这个网站会有更多的50个产品。

1 个答案:

答案 0 :(得分:3)

我觉得这样的事情应该有效......

SELECT
  product.title,
  product.url_name,
  product.description,
  A.price,
  image.thumbnail
FROM
  mps_contents AS product
  LEFT OUTER JOIN
    mps_contents AS image 
    ON
      image.page_id = product.content_id AND
      image.display_order = '1' AND
      image.resource_type = 'image'
  LEFT OUTER JOIN (
      SELECT price.price 
      FROM mps_contents AS model 
      JOIN mps_product_info price ON (model.content_id = price.content_id) 
      WHERE model.page_id = product.content_id 
      ORDER BY price.price
      LIMIT 1
  ) AS A
WHERE
  product.active = '1' AND
  product.resource_type = 'product' AND
  product.featured = '1'
ORDER BY RAND( )
LIMIT 3