MySQL UPDATE,MAX,JOIN查询

Jas*_*son 7 mysql sql

我有两张桌子: -

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

product_table
product_id, score
1, 80
2, 60
3, 40
Run Code Online (Sandbox Code Playgroud)

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

summary_table
manufacturer, max_score
ford,   1
toyota, 3
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有: -

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;
Run Code Online (Sandbox Code Playgroud)

有麻烦...所有的帮助都非常感激.

Gar*_*thD 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
        )
Run Code Online (Sandbox Code Playgroud)

  • 这不是我真正的意思,我预计上述查询最多需要 1 小时。请记住,外键不是索引,因此可能需要与密钥一起创建索引,实际上,我希望对 1100 万行进行如此简单的更新需要几秒钟,也许几分钟,但肯定不会几个小时 (2认同)