John James
John James

Reputation: 657

UPDATE and SELECT from same table in one query

I am trying to count the rows from table1, and depending the rows count to update a certain column. Below is the query I have tried, but am getting an arror saying that temp is not a table.

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

Upvotes: 0

Views: 446

Answers (2)

Abhilash Ravindran C K
Abhilash Ravindran C K

Reputation: 1856

Following query will be helpful to you,

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)

Upvotes: 1

Crutches
Crutches

Reputation: 179

A couple things:

  1. I would suggest making a temp table of the data in your case statement, then joining that for an update.

  2. Joining back on the table you're updating does not work.

  3. You have a syntax error in your where clause. You don't need that equals sign before IN.

Try:

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); 

Upvotes: 1

Related Questions