MySQL UPDATE,MAX,JOIN查询

时间:2012-02-22 14:18:56

标签: mysql sql

我有两张桌子: -

manu_table
product_id, manufacturer
1, ford
2, ford
3, toyota

product_table
product_id, score
1, 80
2, 60
3, 40

我想在摘要表中为每个制造商存储得分最高的product_id: -

summary_table
manufacturer, max_score
ford,   1
toyota, 3

到目前为止,我已经: -

UPDATE summary_table st
SET max_score = (
                 SELECT product_id 
                 FROM (
                       SELECT manufacturer, product_id, max(score) as ms 
                       FROM manu_table 
                       LEFT JOIN product_table USING (product_id) 
                       group by product_id) t)
WHERE st.manufacturer = manu_table.manufacturer;

遇到麻烦......非常感谢所有帮助。

2 个答案:

答案 0 :(得分:3)

尝试此查询 -

UPDATE summary_table st
  JOIN (
    SELECT mt.manufacturer, MAX(pt.score) max_score FROM manu_table mt
    JOIN product_table pt
      ON mt.product_id = pt.product_id
    GROUP BY mt.manufacturer) t
  ON t.manufacturer = st.manufacturer
SET st.max_score = t.max_score

此查询将product_id设置为最高得分:

UPDATE summary_table st
  JOIN (SELECT t1.* FROM 
  (SELECT mt.*, pt.score FROM manu_table mt JOIN product_table pt ON mt.product_id = pt.product_id) t1
  JOIN (
    SELECT mt.manufacturer, MAX(pt.score) max_score FROM manu_table mt
     JOIN product_table pt
       ON mt.product_id = pt.product_id
     GROUP BY mt.manufacturer
  ) t2
  ON t1.manufacturer = t2.manufacturer AND t1.score = t2.max_score
  ) t
  ON t.manufacturer = st.manufacturer
SET st.max_score = t.product_id

答案 1 :(得分:2)

我理解这个问题我认为这会有效,我使用MAX(Product_ID)只是为了解决任何重复问题,其中同一制造商的2个产品可能具有相同的分数,并且都是最高分。您可能希望以不同方式解决重复项。

UPDATE  summary_table
SET     max_score = 
        (   SELECT  MAX(m.Product_ID) [MaxScoreProductID] 
            FROM    manu_table m
                    INNER JOIN product_table p
                        ON m.Product_ID = p.Product_ID
                    INNER JOIN
                    (   SELECT  Manufacturer, MAX(Score) [MaxScore]
                        FROM    manu_table m
                                LEFT JOIN product_table p
                                    ON m.Product_ID = p.Product_ID
                        GROUP BY Manufacturer
                    ) ms
                        ON ms.Manufacturer = m.Manufacturer
                        AND ms.MaxScore = p.Score
            WHERE   m.Manufacturer = summary_table.Manufacturer
            GROUP BY m.Manufacturer
        )