开发者

pure MySQL loop to update multiple rows

I want to update multiple rows based on a SELECT sql query.

I want to do it ALL IN AN SQL SHELL!

Here is my select:

SELECT @myid := id, @mytitle := title
FROM event 
WHERE pid>0 GROUP BY title
ORDER BY start;

Then, I want to do an update with this pseudocode:

foreach($mytitle as $t)
BEGIN
    UPDATE event
    SET pid=$myid
    WHERE title=$t;
END
开发者_运维技巧

But I don't know how to ake a loop in SQL.

Maybe there's a way to make it in a single sql query?

I DON'T WANT ANY PHP!!! ONLY SQL SHELL CODE!!!


I want to update every rows with a pid with the id of the first occurence of an event. Start is a timestamp

I think this should do what you want, but if it doesn't (I'm not sure about joining a subquery in an UPDATE query) then you can use a temporary table instead.

UPDATE
    event
    JOIN (
        SELECT
            MIN(pid) AS minPID,
            title
        FROM
            event
        WHERE
            pid > 0
        GROUP BY
            title
    ) AS findPIDsQuery ON event.title = findPIDsQuery.title
SET
    event.pid = findPIDsQuery.minPID


Pure SQL doesn't really have "loops", per se: it's a set-based descriptive language. I believe the following update will do what you want (though your problem statements leaves much to be desired—we know nothing about the underlying schema).

update event t
set pid = ( select min(id)
            from event x
            where x.title = t.title
              and x.pid > 0
            group by x.title
            having count(*) > 1
          )

Cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜