views:

36

answers:

2

This may be a stupid question but is it possible to store a count query in a field in a table such that when the result of the count changes the result will update itself?

Thread(ThreadID,NumMessages)  
Message(MessageID,ThreadID,MessageText,PreviousMessage)

I want to update the Thread.NumMessages field any time a message with the corresponding ThreadID gets added or removed. I know I can do this by incrementing/decrementing the Thread.NumMessages field of by using a count query

SELECT COUNT(*), FROM SCHEMA.Message WHERE ThreadID='SOMETHREADID'

But is there anyway of setting up the NumMessages field so this is kept up to date without it being done explicitly at every addition and delete?

Thanks Graeme

+4  A: 

yes, you can use a view as the implementation of your Thread table.

http://dev.mysql.com/doc/refman/5.1/en/create-view.html

Create view thread_view 
    select 
        count(*) as NumMessages, 
        threadID 
        from message 
        group by threadID
Zak
+1: You beat me to it
OMG Ponies
that's ok you've beat me to it about 3100 other times :)
Zak
Thanks guys but for this exact purpose triggers suit me better but I will spend some time looking into both views and triggers as soon as I have time :)
Graeme Smyth
+1  A: 

Triggers!

You're wanting a trigger. This should help you with your searching (knowing what to look for is half the battle). http://www.databasedesign-resource.com/mysql-triggers.html

Basically, a trigger fires any time a designated event (such as insert) on a table is tripped, and executes a stored procedure.

your stored procedure would then check to make sure it's something it cares about (you can add all sorts of logic here), then does something (increment that value?) before MySQL executes the original query that triggered it in the first place.

http://www.roseindia.net/mysql/mysql5/triggers.shtml

Caladain
Use a view before you think of triggers.
OMG Ponies
Thank you very much :) I had heard the term trigger before but never used them, they are just what I need for now :)
Graeme Smyth