0

This SHOULD be trivial but I am going round in circles, perhaps someone can help.

I have two tables (T1, T2) from which I wish to extract a number of values in each row and update the contents of a third table (T3) iff (if and only if) two UQ, NN fields in T1, T2 match, in which case I want to add some of the values in the corresponding rows from T1, T2 together and put them in T3 and copy some other values over to T3.

The fields to be summed are all declared DECIMAL.

Simplified and in pseudocode (to avoid making too many assumptions):

SELECT T1.a,T1.b,T1.c from T1

SELECT T2.d, T2.e from T2

UPDATE T3.col1=a, T3.col2=b, T3.col3 = (value of(T2.c) + value of(T2.e)) iff T1.a = T2.d 

A variety of attempts have failed to work.

I am running MySQL Workbench 5.2.37 on Ubuntu 12.10


Example from comment below:

UPDATE Test_join as T3 
  SELECT GZHident, Magnitude_1 from GZHTableExtended3 as T1 
  SELECT AHZid, DM from AHZDMConversionTable as T2 JOIN T2,T1 
    ON T1.GZHident = T2.AHZid 
SET T3.AHZid = T1.GZHident 
SET T3.DM = T2.DM 
SET T3.Abs_Magnitude_1 = T1.Magnitude_1 + T2.DM;
4

1 回答 1

0

MySQL 支持使用 JOIN 语法的多表UPDATE,就像 SELECT 一样。这不是标准的 ANSI SQL,但它对于这些类型的情况非常有用。

例子:

UPDATE T1
JOIN T2 ON T1.a = T2.d
JOIN T3 ON ...???...
SET T3.col1=T1.a, 
    T3.col2=T1.b,
    T3.col3 = T2.c + T2.e;

您的问题中没有足够的信息让我猜测如何加入 T3。


感谢您发布示例 UPDATE 查询。但目前还不清楚您要如何更新 T3。您提供的示例查询根本不是有效的 SQL 代码。我建议您阅读有关 SQL 编程的教程。

您似乎对 UPDATE 和 INSERT 感到困惑?记住:

  • INSERT 添加新行。
  • UPDATE 更改现有行中的值。

我从你的措辞猜测,但也许你想添加新行。你可以这样做:

INSERT INTO Test_join (AHZid, DM, Abs_Magnitude)
SELECT T1.GZHident, T2.DM, T1.Magnitude_1 + T2.DM
FROM GZHTableExtended3 as T1
JOIN AHZDMConversionTable as T2 JOIN T2 
  ON T1.GZHident = T2.AHZid;
于 2013-10-17T02:09:24.980 回答