开发者

sql update table that has sequencing stored in it

I am trying to update a DB table with the following structure:

user_id, group_id, other_data, sequence

user_id points to a user table with all of the user data, and group_id points to a record in a group info table. other_data is nothing important. sequence is a value that is used to determine in what order users are listed. For instance, if I pull everyone from group_id 1234, the sequence is used to order them by.

I am trying to run an update to change this sequence when a user is deleted from the table. Currently, I am working with a CFML script that runs a SELECT query, loops through it, and then does individual updates. What I want to do is write the whole thing in one query.

The issue that comes up is when a user is in more than one group (which is usually the case). This is what I currently have:

UPDATE
    user_groups_tbl
SET
    sequence = sequence - 1
WHERE
        group_id IN (SELECT group_id FROM user_groups_tbl WHERE user_id = #URL.user_id#)
    AND
        sequence > (SELECT sequence FROM user_groups_tbl WHERE user_id = #URL.user_id#);

I can tell that with this query, the WHERE for the sequence is not right; this will pull some "开发者_如何学Crandom" sequence number, not particularly the one that is tied to the record with the proper group_id.

I don't know if I have explained this well enough, hopefully someone will be able to see what I'm trying to do here with this... If anyone can help with the query, it would be much appreciated.

This is currently being run on a MS SQL 2005 server, but will eventually be ported over to a MySQL engine.


tI think this will get it:

UPDATE
    user_groups_tbl
SET
    sequence = sequence - 1
WHERE
        group_id IN (SELECT group_id FROM user_groups_tbl
                     WHERE user_id = #URL.user_id#)
    AND
        sequence > (SELECT tbl2.sequence FROM user_groups_tbl tbl2
                    WHERE tbl2.user_id = #URL.user_id#
                       AND tbl2.group_id = user_groups_tbl.group_id);

I added another condition to the second half of your where clause to restrict what Group_id the subquery will return. This required adding a table alias.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜