使用从计算另一个表中提取的值更新mysql行

时间:2012-10-30 07:12:44

标签: mysql sql sql-update

我有以下查询:

SELECT int_intrebari.id, COUNT( id_raspuns ) AS nr_raspunsuri
FROM int_intrebari, int_raspunsuri
WHERE int_intrebari.id = int_raspunsuri.id
GROUP BY id

是否可以从查询中使用nr_raspunsuri更新第一个表,而无需编写foreach语句?

3 个答案:

答案 0 :(得分:2)

UPDATE JOIN可以这样:

UPDATE int_intrebari i1
INNER JOIN
(
    SELECT id, COUNT( id_raspuns ) AS nr_raspunsuri
    FROM int_intrebari
    GROUP BY id 
) i2 ON i1.id = i2.id
SET i1.nr_raspunsuri = i2.nr_raspunsuri

答案 1 :(得分:1)

你可以这样做 -

update int_intrebari left join int_raspunsuri on int_intrebari.id =int_raspunsuri.id
set int_intrebari.column_to_update = int_raspunsuri.column_from_update_second_table

答案 2 :(得分:0)

UPDATE
  (SELECT int_intrebari.id, COUNT( id_raspuns) AS nr_raspunsuri
   FROM int_intrebari, int_raspunsuri
   WHERE int_intrebari.id = int_raspunsuri.id
   GROUP BY id) t1,
  int_raspunsuri t2
SET
  t2.nr_raspunsuri=t1.nr_raspunsuri
WHERE
  t1.id=t2.id