MySQL 使用带 ORDER BY 和 LIMIT 的 INNER JOIN 进行更新

MySQL Update using INNER JOIN with ORDER BY and LIMIT

我正在尝试使用带有限制和排序依据的内部联接进行更新(尽管排序依据不是必需的。根据我的阅读,标准更新将不起作用...这就是我我正在尝试做:

UPDATE table1
INNER JOIN table2
ON table1.service_id=table2.service_id
SET table1.flags = NULL
WHERE table1.type = 'fttc'
AND table1.flags = 'co'
AND table2.sync not like '%Yes%'
AND table1.date >= $today_date
ORDER BY table1.priority ASC
LIMIT 20;

它用于案例管理工具并使用 php,我想更新 20 张工单,即删除 'flag' 以便它们可以工作,数量将作为变量,所以我想先更新 20 张票,例如最高 'priority',如果可以的话?

如果我没看错你的问题,你想对连接产生的前 20 条记录执行更新,使用优先级作为排序。您不能直接在 MySQL AFAIK 中的 UPDATE 中执行此操作,但您可以创建一个可更新的视图,然后更新它。

CREATE VIEW yourView
AS
SELECT
    t1.service_id,
    t2.service_id,
    t1.flags,
    t1.type,
    t1.date,
    t1.priority,
    t2.sync
FROM table1 t1
INNER JOIN table2 t2
    ON t1.service_id = t2.service_id
WHERE t1.type = 'fttc'         AND
      t1.flags = 'co'          AND
      t2.sync NOT LIKE '%Yes%' AND
      t1.date >= $today_date
ORDER BY t1.priority
LIMIT 20;

然后更新此视图:

UPDATE yourView
SET flags = NULL

应该没有理由使用视图:

UPDATE table1 t1
    SET t1.flags = NULL
    WHERE t1.type = 'fttc' AND
          t1.flags = 'co' AND
          t1.date >= $today_date AND
          EXISTS (SELECT 1
                  FROM table2 t2
                  WHERE t2.service_id = t1.service_id AND
                        t2.sync not like '%Yes%'
                 )
    ORDER BY t1.priority ASC
    LIMIT 20;

您不能将 ORDER BYLIMIT 与多个 table JOIN 一起使用。但是,您可以将 table2 上的条件移动到 WHERE 子句。

我的以下工作:

UPDATE child AS upd
 JOIN (SELECT t1.id FROM child AS t1
 INNER JOIN master AS t2
 ON t2.id = t1.id
   where 1
   AND t2.`date` BETWEEN '2020-06-23 00:00:00' AND '2020-06-23 23:59:59' 
   AND t2.client_id= 10 AND t1.code NOT IN('11','22')
 order by t1.id desc LIMIT 1) AS col
 ON upd.id=col.id 
 SET upd.code= '33', upd.`resp` = 'done',upd.status='success'