update语句

yzckvree  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(323)
SELECT
    vl1.phone_number,
    vl1.first_name,
    CONCAT(
        SUBSTRING(
            (
            SELECT
                vl2.phone_number 
            FROM
                list as vl2
            WHERE
                vl2.phone_number LIKE CONCAT( SUBSTRING( vl1.phone_number FROM 1 FOR 3 ), "%" ) 
            ORDER BY
                RAND( ) 
                LIMIT 1 
            ) 
        FROM
            1 FOR 6 
        ),
        FLOOR( RAND( ) * ( 8999 ) ) + 1000 
    ) AS autogenNumber 
FROM
    list as vl1
LIMIT 1

我得到的结果是

phone_number | firstname | autogenNumber

通过首先搜索共享前三个数字的其他数字来生成自生号码。然后从该数字中选取6个数字,并将另外4个随机数字替换到最后。
上面的sql查询完全按照我的需要生成autogen编号。
但是,现在当我想使用下面类似的查询更新这个列表中的列security\u短语时,问题就出现了。

UPDATE list as vl1
SET vl1.security_phrase = (
    CONCAT(
        SUBSTRING(
            (
                SELECT
                    vl2.phone_number 
                FROM
                    list AS vl2 
                WHERE
                    vl2.phone_number LIKE CONCAT( SUBSTRING(phone_number FROM 1 FOR 3 ), "%" ) 
                ORDER BY
                    RAND( ) 
                    LIMIT 1 
                ) 
            FROM
                1 FOR 6 
            ),
            FLOOR( RAND( ) * ( 8999 ) ) + 1000 
        ) 
    ) 
    LIMIT 10

给我一个错误:
1093-表“vl1”被指定两次,既作为“update”的目标,又作为单独的数据源
我也试过了

UPDATE list AS vl1
JOIN list AS vl2 

SET vl1.security_phrase = (
    CONCAT( SUBSTRING( vl2.phone_number FROM 1 FOR 6 ), FLOOR( RAND( ) * ( 8999 ) ) + 1000 ) 
) 
WHERE
    vl2.phone_number LIKE CONCAT( SUBSTRING( vl1.phone_number FROM 1 FOR 3 ), "%" )

不起作用,也不能达到预期效果。。。
有什么帮助吗

v8wbuo2f

v8wbuo2f1#

mysql不允许引用另一个子查询中再次更新的表,除非它在 FROM 子句(派生表)。
现在,在你的特殊情况下,我们需要把 SELECT 作为派生表的查询块。如聊天中所述, lead_id 是您的主键,因此我们将使用pk返回以相应地更新行。

UPDATE list AS t1 
JOIN 
(
  SELECT
    vl1.lead_id,
    CONCAT(
        SUBSTRING(
            (
            SELECT
                vl2.phone_number 
            FROM
                list as vl2
            WHERE
                vl2.phone_number LIKE CONCAT( SUBSTRING( vl1.phone_number FROM 1 FOR 3 ), "%" ) 
            ORDER BY
                RAND( ) 
                LIMIT 1 
            ) 
        FROM
            1 FOR 6 
        ),
        FLOOR( RAND( ) * ( 8999 ) ) + 1000 
    ) AS autogenNumber 
  FROM
    list as vl1
) AS dt 
  ON dt.lead_id = t1.lead_id 
SET t1.security_phrase = dt.autogenNumber

相关问题