mariadb 当一个列具有相同值时,我需要SQL查询

41zrol4v  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(173)

我想运行一个查询,其中所有列number都具有相同的值,并从type的值为0的行中复制其他行中的address值。
例如,在张贴的图像中,number列的值为“1”,将地址从type = 0复制到其他行。这意味着,所有三行中number列的值为1,地址列的值将为ABC、ABC、ABC,同样,在number列中,值为2,地址将为CSA、CSA。

ltskdhd1

ltskdhd11#

如下所示(取type = 0的number的值,并将其联接到主表):

WITH
    t AS (SELECT _number,
                 MAX(_address) AS _address -- here can be more than one row with type = 0 ?
              FROM test
              WHERE _type = 0
              GROUP BY _number)
SELECT test._id,
       test._number,
       test._type,
       t._address
    FROM test
    LEFT JOIN t
            ON test._number = t._number;

下面是dbfiddle示例

**upd.**对于更新,您可以使用以下更新:

UPDATE test
    INNER JOIN (SELECT
    _number,
    max(_address) AS _address -- here can be more than one row with type = 0 ?
    FROM test
    WHERE _type = 0
    GROUP BY _number) t
ON t._number = test._number
SET test._address = t._address;

已更新dbfiddle here

相关问题