对UPDATE查询感到困惑。如何将选择转换为MySQL更新?

时间:2012-05-25 13:44:38

标签: mysql sql

我在这里看到的问题非常相似,但我尝试将后续查询转换为UPDATE语句的尝试失败了。

SELECT table.* FROM table JOIN (
  SELECT   column, COUNT(*) AS rank
  FROM     table
  GROUP BY column
) AS t USING (column) WHERE t.rank = 1
ORDER BY t.rank DESC

我想更新使用上述查询选择的所有结果的列。

如何将其转换为更新语句?

谢谢。

3 个答案:

答案 0 :(得分:2)

这应该这样做:

update table
set column = 'somevalue'
where id in
(select id from (

SELECT table.* FROM table JOIN (
  SELECT   column, COUNT(*) AS rank
  FROM     table
  GROUP BY column
) AS t USING (column) WHERE t.rank = 1) x)

答案 1 :(得分:0)

不完全确定,但我认为它类似于

update tblname set columname = value where tblname.columncompare = (select statement)

答案 2 :(得分:0)

INSERT INTO table (id, value)
SELECT table.id, table.value
FROM table
JOIN (
  SELECT   column, COUNT(*) AS rank
  FROM     table
  GROUP BY column
) AS t USING (column)
WHERE t.rank = 1
ORDER BY t.rank DESC
ON DUPLICATE KEY UPDATE value = VALUES(value)

Insert on duplicate救援!

基本上,这允许你像往常一样做任何SELECT,然后你先插入INSERT INTO并附加ON DUPLICATE。

我想这个查询已经完成,但过滤和排序同一列的重点是什么?