MYSQL查询来自另一个表的相关数据

时间:2017-03-25 19:50:39

标签: mysql sql where

我想从另一个表中查询相关数据,在那里我可以获得最低的相关值......

两个表的示例

products
id          name          description
0           product_1     short description of 1
1           product_2     short description of 2

prices
id          product_id          option        price       personal
0           1                   3             10.00       1
1           0                   2             15.00       1
2           1                   3             5.00        0
3           1                   3             8.00        0
4           0                   2             7.00        1

需要输出

id          name          description       price     option
0           product_1     short ...         7.00      2
1           product_2     short ...         10.00     3

我基本上尝试制作的查询是获取所有相关字段的查询,从个人= 1且价格最低的价格中获取相关数据。

当前查询(获得最低价但未关联的选项)

SELECT products.*, prices.option, 
   (SELECT ROUND( MIN( price ), 2) FROM prices WHERE product_id = products.id AND personal = 1) AS price 
FROM products 
ORDER BY price_low ASC

3 个答案:

答案 0 :(得分:1)

如何使用联接而不是子查询并按产品分组?看起来应该是这样的:

SELECT products.*, ROUND(MIN(prices.price), 2), prices.option
FROM products
INNER JOIN prices ON products.id = prices.product_id
WHERE prices.personal = 1
GROUP BY products.id

我在SqlFiddle上试了here are the results

答案 1 :(得分:0)

你可以使用内部联接和subselect with和group by来获得最低价格

SELECT p.id, p.name, p.description, pr.option, pr.price 
FROM products as p
inner join ( 
  select product_id, min(price) as price 
  from price 
  where personal = 1
  group by product_id

  ) t  on t.product_id= p.id
inner join price as pr on pr.product_id = p.id and pr.price = t.price
where pr.personal =1
group by   p.id, p.name, p.description, pr.option
ORDER BY pr.price ASC

答案 2 :(得分:0)

感谢您对此问题的反馈。经过大量的追踪和错误后,我终于得到了所需的结果,这里是:

SELECT products.*, b.*, products.id as id FROM `products` 
LEFT JOIN 
    (SELECT * FROM 
        ( SELECT * FROM prices ORDER BY product_id ASC, price ASC ) 
    as c GROUP BY product_id) 
AS b ON b.product_id = products.id 
WHERE `price` IS NOT NULL ORDER BY `product_id` ASC
相关问题