0

以前にストアド プロシージャを作成したことがありません。キーを共有するテーブル B のレコード数の結果でテーブル A のフィールドを更新するにはどうすればよいですか?

Table A is a "users" table with a Primary key "userid" and a field "rentals_count". Table B is a "rentals" table with a Foreign Key "userid"

For each user (record) in Table A update the "rentals_count" field with the sum of rentals in Table B that match that user as an integer.

The question includes the mechanics of actually implementing and running the stored procedure on a nightly basis.

4

1 に答える 1

2

為にSQL Server

CREATE PROCEDURE UpdateTableA
AS
UPDATE  a
SET     a.rentals_count = b.totalCount
FROM    TableA a
        INNER JOIN
        (
            SELECT  userID, Count(*) totalCount
            FROM    TableB
            GROUP   BY userID
        ) b ON a.userID = b.userID

為にMySQL

UPDATE  TableA a
        INNER JOIN
        (
            SELECT  userID, Count(*) totalCount
            FROM    TableB
            GROUP   BY userID
        ) b ON a.userID = b.userID
SET     a.rentals_count = b.totalCount

于 2013-03-05T13:15:04.017 に答える