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

时间:2017-04-17 09:50:45

标签: mysql sql sql-order-by inner-join 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例如,如果可以做的话,首先是最高'优先​​'的门票?

3 个答案:

答案 0 :(得分:3)

如果我正确阅读了您的问题,您希望对连接产生的前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

答案 1 :(得分:2)

没有理由使用视图:

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与多表JOIN一起使用。但是,您可以将table2上的条件移至WHERE子句。

答案 2 :(得分:0)

为我工作:

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'