简体   繁体   English

MySQL结合了UPDATE和SELECT查询

[英]MySQL combine UPDATE and SELECT query

I have the following SELECT statement that returns data, example below: 我有以下返回数据的SELECT语句,示例如下:

SELECT performers.ID, 
       performers.Name, 
       COUNT(*) AS CountOfDeals, 
       COUNT(DISTINCT(deals.Name)) AS CountOfAliases 
  FROM deals RIGHT JOIN performers 
               ON deals.name LIKE CONCAT('%', performers.name, '%') 
 WHERE performers.ID IN ( 27952, 27951, 27950, 27949, 27948 ) 
 GROUP BY Name;

Example data returned: 返回的示例数据:

  ID        Name             CountOfDeals     CountOfAliases
27952   Christine Hoberg          1                 0
27951   Indian Jewelry            1                 0
27952   Kinky Friedman            5                 3
27949   KJ-52                     1                 0
27960   River Whyless             1                 0

I want to combine this with the following UPDATE statement 我想结合以下UPDATE语句

UPDATE performers 
   SET RawAliasCount = CountOfAliases, 
       RawDealCount = CountOfDeals 
 WHERE ID = ?

All the values needed to run the update statement are returned in the select statement above so hopefully this should be pretty easy. 在上面的select语句中返回了运行update语句所需的所有值,因此希望这应该很容易。

Thanks. 谢谢。

Use update with join : 使用带有join update

UPDATE performers p JOIN
       (SELECT performers.ID, performers.Name, COUNT(*) AS CountOfDeals, 
               COUNT(DISTINCT(deals.Name)) AS CountOfAliases 
        FROM deals RIGHT JOIN
             performers
             on deals.name LIKE CONCAT('%', performers.name, '%') 
        WHERE performers.ID IN (27952, 27951, 27950, 27949, 27948) 
        GROUP BY Name
       ) pp
       ON pp.id = p.id
    SET RawAliasCount = pp.CountOfAliases,
        RawDealCount = pp.CountOfDeals;
UPDATE  performers
SET performers.RawAliasCount = count_table.CountOfAliases, performers.RawDealCount = count_table.CountOfDeals
FROM   performers
        INNER JOIN
        (
            SELECT 
            performers.ID, performers.Name, COUNT(*) AS CountOfDeals, 
            COUNT(DISTINCT(deals.Name)) AS CountOfAliases 
            FROM deals RIGHT JOIN performers on deals.name LIKE CONCAT('%', performers.name, '%') 
            WHERE performers.ID IN (27952, 27951, 27950, 27949, 27948) 
            GROUP BY Name
        ) count_table
ON count_table.ID = performers.ID;

When this type of question is asked, thank you to put the tables schema. 当询问这种类型的问题时,谢谢您放入表模式。

edit : sorry, it's sql-server syntax. 编辑:抱歉,这是sql-server语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM