在一个查询中从同一个表更新和SELECT

时间:2018-01-11 01:57:37

标签: mysql select join sql-update

我正在尝试计算table1中的行数,并根据行计数来更新某个列。下面是我试过的查询,但是我得到一个恐怖的说法,temp不是一张桌子。

UPDATE table1 AS t1
INNER JOIN table1 AS temp ON temp.id = t1.id
SET
t1.field1 = (CASE
    WHEN (SELECT COUNT(*) FROM temp WHERE temp.field1 = 1) < 100 THEN 1
    WHEN (SELECT COUNT(*) FROM temp WHERE temp.field1 = 2) < 100 THEN 2
    WHEN (SELECT COUNT(*) FROM temp WHERE temp.field1 = 3) < 100 THEN 3
    WHEN (SELECT COUNT(*) FROM temp WHERE temp.field1 = 4) < 100 THEN 4
    WHEN (SELECT COUNT(*) FROM temp WHERE temp.field1 = 5) < 100 THEN 5
END)
WHERE t1.id IN(100, 200, 300); --Example data

2 个答案:

答案 0 :(得分:1)

一些事情:

  1. 我建议在你的情况下制作数据的临时表 声明,然后加入更新。

  2. 重新加入桌面,您的更新无效。

  3. 您的where子句中存在语法错误。你不需要那个 IN之前的等号。

  4. 尝试:

    DROP TABLE IF EXISTS temp_table1;
    CREATE TEMPORARY TABLE temp_table1 AS
    SELECT field1,count(*) as field_count FROM table1 group by field1;
    
    UPDATE table1 AS t1
    LEFT JOIN temp_table1 aa
      ON aa.field1= t1.field1
    SET t1.field1 = (CASE 
      WHEN aa.field1 = 1 AND aa.field_count < 100 THEN 1 
      WHEN aa.field1 = 2 AND aa.field_count < 100 THEN 2 
      WHEN aa.field1 = 3 AND aa.field_count < 100 THEN 3 
      WHEN aa.field1 = 4 AND aa.field_count < 100 THEN 4 
      WHEN aa.field1 = 5 AND aa.field_count < 100 THEN 5 END)
    WHERE t1.id IN (100, 200, 300); 
    

答案 1 :(得分:1)

以下查询对您有所帮助,

UPDATE table1 as t1
SET
t1.field1 = (CASE         
    WHEN (select p.cnt from (SELECT COUNT(*) as cnt FROM table1 t2 WHERE t2.field1= 1) as p) < 100 THEN 1
    WHEN (select p.cnt from (SELECT COUNT(*) as cnt FROM table1 t2 WHERE t2.field1= 2) as p) < 100 THEN 2
    WHEN (select p.cnt from (SELECT COUNT(*) as cnt FROM table1 t2 WHERE t2.field1= 3) as p) < 100 THEN 3
    WHEN (select p.cnt from (SELECT COUNT(*) as cnt FROM table1 t2 WHERE t2.field1= 4) as p) < 100 THEN 4
    WHEN (select p.cnt from (SELECT COUNT(*) as cnt FROM table1 t2 WHERE t2.field1= 5) as p) < 100 THEN 5    
 END)
WHERE t1.id IN(100, 200, 300)