<p>Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).</p>

<pre><code>CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`date` DATETIME NOT NULL ,
`count` INTEGER NOT NULL ,
PRIMARY KEY (`id`)
);
</code></pre>

<p>Is it possible to have the count column calculated for me whenever I do an insert?</p>

<p>e.g. do something like:</p>

<pre><code>INSERT INTO log (date='foo');
</code></pre>

<p>and have count calculated by mysql.</p>

<p>Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better.</p>

[{'answer_id': 45382, 'author': 'Thomas Watnedal', 'author_id': 4059, 'author_profile': 'https://Stackoverflow.com/users/4059', 'pm_score': 0, 'selected': False, 'text': '<p>You definitly have to declare what to insert. This should be possible by using the <a href="http://dev.mysql.com/doc/refman/5.1/en/insert-select.html" rel="nofollow noreferrer" title="INSERT .... SELECT">INSERT ... SELECT</a> statement. </p>\n\n<pre><code>INSERT INTO log (date, count)\n    SELECT DATE() as date, count(id) as count\n    from foo;\n</code></pre>\n\n<p>Which should insert a new row into the log table, containing todays date and the number of  rows in the foo table. (Assuming the foo table has an id column.. Use the primary key or another indexed column)</p>\n'}, {'answer_id': 61050, 'author': 'Joe Mahoney', 'author_id': 575, 'author_profile': 'https://Stackoverflow.com/users/575', 'pm_score': 4, 'selected': True, 'text': "<p>Triggers are the best tool for annotating data when a table is changed by insert, update or delete.</p>\n\n<p>To automatically set the date column of a new row in the log with the current date, you'd create a trigger that looked something like this:</p>\n\n<pre><code>create trigger log_date before insert on log \nfor each row begin\n   set new.date = current_date()\nend;\n</code></pre>\n"}, {'answer_id': 16204323, 'author': 'Federico Razzoli', 'author_id': 1090198, 'author_profile': 'https://Stackoverflow.com/users/1090198', 'pm_score': -1, 'selected': False, 'text': "<p>Why don't you use information_schema.TABLES?</p>\n"}]
['https://Stackoverflow.com/questions/45372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1666/']