返回并更新具有不同用户创建者的MySQL行。

huangapple go评论48阅读模式
英文:

Return & UPDATE mysql rows with different user creator

问题

UPDATE 语句的语法不正确,以下是正确的更新语句:

UPDATE posts
SET status = 0
WHERE id_user IN (343, 345, 356)
ORDER BY date ASC
LIMIT 3;

这个更新语句将会更新每个用户(id_user 为 343、345、356)的前三条记录,根据日期升序排列。

英文:

Ok, I have the next table "posts"

id_user  id_post   post                date                         status

343      34534    Hi                 2023-01-01  01:00:00           1
343      232324   Hello              2023-01-01  02:00:00           1
343       32423   How are you?       2023-01-01  03:00:00           1
345      345454   Whats up?          2023-01-01  04:00:00           1
345     3457543   Was geth ab?       2023-01-01  05:00:00           1
356      454354   Wie geth's?        2023-01-01  06:00:00           1

Ok I want to update the first row of each user (343,345 & 356) based on the date

 UPDATE  posts SET status = 0 WHERE 1 ORDER BY date ASC LIMIT 3

Expected result

Hi                 2023-01-01  01:00:00
Whats up?          2023-01-01  04:00:00
Wie geth's?        2023-01-01  06:00:00

I tried

UPDATE posts p 
WHERE 1 
LEFT JOIN post c ON p.id_user !=c.id_user 
ORDER BY date ASC LIMIT 3

But it doesnt work, what am I doing wrong?

答案1

得分: -2

你可以以类似的方式来执行,就像你选择每个组中的第一/最后一行一样:

UPDATE posts AS p1
JOIN (
    SELECT id_user, MIN(date) AS mindate
    FROM posts
    GROUP BY id_user
) AS p2 ON p1.id_user = p2.id_user AND p1.date = p2.mindate
SET p1.status = 0

需要执行一个单独的查询来返回它们,因为MySQL没有提供直接返回已更新行的方法。

SELECT *
FROM posts
WHERE status = 0
英文:

You do it similarly to the way you select the first/last row in a each group

UPDATE posts AS p1
JOIN (
    SELECT id_user, MIN(date) AS mindate
    FROM posts
    GROUP BY id_user
) AS p2 ON p1.id_user = p2.id_user AND p1.date = p2.mindate
SET p1.status = 0

You'll need to do a separate query to return them, because MySQL doesn't provide a way to return the rows that were updated directly.

SELECT *
FROM posts
WHERE status = 0

huangapple
  • 本文由 发表于 2023年7月10日 23:46:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76655359.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定