简体   繁体   中英

Update count ID values in one table and display in column of another

UPDATE CD
    SET cdNumOfTracks = (
        SELECT COUNT(cdID)
            FROM Track
        WHERE Track.cdID = CD.cdID
        GROUP BY cdID
        );

The query above I am using to count the 'cdID' from a table "Track" and have it display this count in the "CD" table as the column 'cdNumOfTracks'. 'cdID' is a foreign key in the "Track" table and comes from the "CD" table. The query works fine but I would have to run this manually to update the data.

I am using this database as part of a website which takes the data through PHP/HTML forms, so therefore I need the SQL backend to update automatically.

For this to be working properly, I would need to be able to add a track, giving it a 'cdID' and this would then add 1 to the 'cdNumOfTracks' column as a new track was added

The answer to your question is to use a trigger. You need a trigger (at least) for inserts and deletes, and possibly for updates. Unless you have a very large database, I would recommend just getting the count directly from CD .

I do want to note something. Because of the group by , your query will return NULL instead of 0 if there are no matches. Generally, correlated subqueries do not use group by :

UPDATE CD
    SET cdNumOfTracks = (SELECT COUNT(cdID)
                         FROM Track
                         WHERE Track.cdID = CD.cdID
                        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM