MySQL中的SELECT查询案例

时间:2018-03-14 23:52:17

标签: mysql select sql-update case

我有一个更新查询,在里面,我想根据它的行数更新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 = 19行, column1 = 27行。

预期结果应该是;

  • 当num = xx1 column1 = NULL
  • 当num = xx2 column1 = 1
  • 当num = xx3 column1 = 2
  • 当num = xx4 column1 = 2

实际结果是;

  • 当num = xx1 column1 = NULL
  • 当num = xx2 column1 = NULL
  • 当num = xx3 column1 = NULL
  • 当num = xx3 column1 = NULL

编辑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: 问题可能是因为我在事务中使用了上述查询,从而禁用了自动提交。

1 个答案:

答案 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
;