我有一个更新查询,在里面,我想根据它的行数更新column1。
我尝试了以下内容,但它似乎没有起作用。它只是将它们全部添加到NULL
。
UPDATE table AS t1 SET
t1.column1 = (CASE
WHEN (SELECT COUNT(*) As cnt FROM table t2 WHERE t2.column1 IS NULL AND t2.uq_id = t1.uq_id) < 10 THEN NULL
WHEN (SELECT COUNT(*) As cnt FROM table t2 WHERE t2.column1 = 2 AND t2.uq_id = t1.uq_id) < 10 THEN 2
WHEN (SELECT COUNT(*) As cnt FROM table t2 WHERE t2.column1 = 3 AND t2.uq_id = t1.uq_id) < 10 THEN 3
WHEN (SELECT COUNT(*) As cnt FROM table t2 WHERE t2.column1 = 4 AND t2.uq_id = t1.uq_id) < 10 THEN 4
WHEN (SELECT COUNT(*) As cnt FROM table t2 WHERE t2.column1 = 5 AND t2.uq_id = t1.uq_id) < 10 THEN 5
ELSE t1.column1
END)
WHERE t1.num IN (xx1, xx2, xx3, xx4) AND t1.uq_id = xxx;
修改
例如:
考虑到什么时候
column1 = NULL
它有9
行,
column1 = 1
有9
行,
column1 = 2
有7
行。
预期结果应该是;
实际结果是;
编辑2:
我还尝试了以下操作来删除所有WHEN
s
t1.column1 = (SELECT column1
FROM table
WHERE (
SELECT column1
FROM table t2
WHERE t2.uq_id = t1.uq_id
GROUP BY column1
HAVING COUNT(*) < 10
ORDER BY column1 ASC
LIMIT 1
) p
)
我理解的问题是,当第一个num
更新时,行的计数不是(?),因此当column1 = NULL时,它仍然有9行计数,直到结束此更新。
编辑3: 问题可能是因为我在事务中使用了上述查询,从而禁用了自动提交。
答案 0 :(得分:0)
这会满足您的要求吗?
UPDATE `table` AS t1 LEFT JOIN (
SELECT t2.uq_id, t2.column1
FROM `table` t2 WHERE t2.column1 IN (NULL,2,3,4,5)
GROUP BY t2.column1 HAVING COUNT(*)<10
) _t2 ON _t2.uq_id=t1.uq_id
SET t1.column1 = _t2.column1
WHERE t1.num IN (xx1, xx2, xx3, xx4) AND t1.uq_id = xxx
;