有多个联接的更新语法

时间:2018-01-12 17:02:20

标签: mysql sql

我在使用多个连接选择更新表时遇到问题。我觉得一切都已到位,但我在最后会遇到一些语法问题,如下所示。

    UPDATE ambition.ambition_totals a
    INNER JOIN (SELECT 
                  c.user AS UserID,
                  COUNT(*) AS dealers,
                  ROUND((al.NumberOfDealers / al.NumberOfDealerContacts) * 100 ,2)  AS percent
          FROM contact_events c
          JOIN users u
          ON c.user = u.id
          JOIN dealers d
          ON c.dealer_num = d.dealer_num
            LEFT JOIN (
              SELECT user_id, COUNT(*) AS NumberOfDealerContacts,
              SUM(CASE WHEN ( d.next_call_date + INTERVAL 7 DAY) THEN 1 ELSE 0 END) AS NumberOfDealers
                  FROM attr_list AS al
                     JOIN dealers AS d ON d.csr = al.data
                       WHERE al.attr_id = 14
                       GROUP BY user_id)) as al
                     ON al.user_id = a.ext_id -- this is where I have a syntax error
      SET a.dealers_contacted = al.dealers,
        a.percent_up_to_date = al.percent;

如图所示,我从这些连接中获取所需的数据,但我无法根据最终连接中的ON子句进行更新。选择本身与此不同,但我只是想改变它以更新表格。

我确定我只是忽略了语法中的某些内容,但我得到一个错误,即每个派生表都必须有自己的别名'。

更新

需要转换为更新的原始工作选择:

    SELECT 
        c.user AS UserID,
        COUNT(*) AS Number_of_recorded_events,
        ROUND((al.NumberOfDealers / al.NumberOfDealerContacts) * 100 ,2)  AS Percentage_up_to_date
    FROM contact_events c
    JOIN users u
    ON c.user = u.id
    JOIN dealers d
    ON c.dealer_num = d.dealer_num
    LEFT JOIN (
      SELECT user_id, COUNT(*) AS NumberOfDealerContacts,
      SUM(CASE WHEN ( d.next_call_date + INTERVAL 7 DAY) THEN 1 ELSE 0 END) AS NumberOfDealers
      FROM jackson_id.attr_list AS al
      JOIN jfi_dealers.dealers AS d ON d.csr = al.data
      WHERE al.attr_id = 14
      GROUP BY user_id) AS al
    ON al.user_id = c.user
    GROUP BY UserID;

1 个答案:

答案 0 :(得分:0)

  

'每个派生表必须有自己的别名'

这个错误很清楚。派生表是将子查询放在FROM子句或JOIN子句中,在查询中执行两次。

每次执行此操作时,必须为每个派生表子查询指定别名,以便引用子查询返回的列。

像:

SELECT t.foo FROM (SELECT foo FROM MyTable) AS t

必须为每个此类子查询执行此操作。在您的情况下,您有类似这样的形式:

UPDATE a 
INNER JOIN (
  SELECT ... FROM c JOIN u JOIN d 
  LEFT JOIN (SELECT ... FROM al JOIN d ...)
) AS al 
SET ...

您有一个级别的子查询,您可以使用别名al

但是你没有为最里面的子查询提供别名,你做了LEFT JOIN。那个人也需要别名。

P.S。:这个问题实际上是2009年What is the error "Every derived table must have its own alias" in MySQL?的重复。我知道如果已经有一个旧的答案,Stack Overflow会鼓励我们将新问题作为重复提出。但我也知道现实是人们往往不会搜索旧帖子。

另一方面,2009年的旧Stack Overflow帖子实际上是我在谷歌搜索错误字符串时的第一个结果'每个派生表必须有自己的别名'。