how to populate column from the content of other columns after a row is inserted in the same table in mysql - mysql

I have a table traffic with 7 columns, namely toll_id, date1, shift, car_single, car_return, car_local and car_total.
How could I populate first 5 columns manually, and then store a value in column car_total, which will be the sum of car_single and car_return?
Here is the image of my table:

Just to add a 3rd and 4th ways of achieving the desired outcome:
If you have at least MySQL v5.7.6, you can use a generated column as car_total.
Alternatively, you can choose not to store car_total at all, but calculate this value on the fly while querying the table.
Having a column to store the results of the calculation is good if you regularly have search based on that field because you can use indexes to speed up the searches. Calculating the results on the fly may be better, if you just need to display the result of the calculation, but there is no need to filter on it.

There are two ways to do this:
Add the logic in the application itself, so that it calculates total before inserting the record. (Recommended)
Write an after insert trigger (http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html) which calculates the count when record is inserted.

Related

How can I create a table that uses an equation to average data from another table?

I have a table that contains data from repeated experiments (for example, site A has one sample, and the lab processed the sample three times obtaining slightly different values). I need to average these results in a separate table, but what I have read on the Microsoft support site is that a query that pulls data into another table with a calculated field is not possible on Access.
Can I query multiple data points from one table into a single calculated field in another table? Thank you.
UPDATE
I ended up doing a lot of manual adjustments of the file format to create a calculated field in the existing table that averages each sites data, so my problem is, for my current purposes, solved. However I would still like to understand. Following up with you both, I think the problem was that I had repeated non-unique IDs between rows when I probably should have made data columns with unique variable names so that I could query each variable name for an average.
So, instead of putting each site separately on the y axis, I formatted it by putting the sample number for each site on the x-axis:
I was able to at least create a calculated field using this second format in order to create an average value for each site.
Would have there been a way to write a query using the first method? Luckily, my data set was not at all very hefty, so I could handle a reformat manually, but if the case were with thousands of data entries, I couldn't have done that.
Also, here is the link to the site I mentioned originally https://support.office.com/en-ie/article/add-a-calculated-field-to-a-table-14a60733-2580-48c2-b402-6de54fafbde3.
Thanks all.

SUM function needs automatically to adjust for changes to SQL DB entries

I'm using multiple Calc tables in a single document for ingoing and outgoing bills that are stored in a SQL DB. Table A has ingoing bills and Table B has outgoing bills. For example table A has data from B2-B39 and table B has data from B2-B15. I need the sum function to automatically adjust when data entries are added or subtracted.
I can use =SUM(B2:B39) in tableA.B40 and =SUM(B2:B15) in tableB.B16 to get the sums of the current data, at the end of the data entries. However, when the DB changes, for example Table A has data from B2-B44, I end up missing five entries. To further complicate things, I have Table C, where I evaluate the net income. For example in Table C I use tableB.B16-tableA.B40. When the number of entries in tables A and B change the function in Table C no longer works.
I need SUM in multiple tables to automatically adjust its position based on how many rows of data are found in the DB.
Maybe there is something about your layout that you have not mentioned but a solution would seem to be to apply whole column references (eg =SUM(B:B)), or if you must have the total in the same column move it to the top and sum like so:
=SUM(B2:B1048576)
Otherwise try something like LibreOffice Basic and search for the first empty cell in the column to put the formula in.

In MySQL, is it more efficient to run my calculation everytime I query the database, or save the values in a new table?

I have a 2-D table of values that I am running through an algorithm to filter out the zero values from the front columns and back columns, and then taking the average across the rows.
In addition to doing this, I am sorting the averages by another column's values.
So in the end, I need a 2xN table with ordered values in my first column and the averages in the 2nd column after filtering out the zero values.
Is the best implementation for this running a routine every query? Or would it be okay for my to run through these computations and then create an entirely new organized table of these values with a foreign key to link it to the other?

Merging several rows based on conditions in MySQL

I have a large database containing informatiom about orders. Each order has a unique number, a tripnumber it is assigned to and a location number.
It sometimes happens that multiple orders are delivered to the same location, during the same trip. I want to merge these entries into one, as they are skewing my analysis results.
I want to iterate over the entire table, checking in every trip whether there are orders that have the same location number. If so, I want to update the rows in MySQL to either add together the values in the columns of that row or take the maximum of the two.
Is this possible in just MySQL?
I am fairly new to using MySQL (and coding in general) so I'm not sure how to write anything that iterates in it.

DBGrid - how to show the differnce between a column value in two adjacent rows as another column?

Let's say I record my car's latitude & longitude every minute or so, adding a row to a table each time.
I want to have a DB grid with 4 columns
latitude
longitude
distance since last measurment
curent street address, if known
Number 4, I can try to retrieve from Google Maps and I either get a text or blank, so let's ignore that.
How do I get #3? Should I calculate it in my application or in MySql (using a stored procedure or just a complicated SELECT)?
Whichever answer, can someone provide some sample code, or a link to an example? Google is not my friend today :-(
You can do it either way:
Calculate it in your query, and display it in a calculated column (such as when showing line totals where you're displaying ITEM_PRICE, QUANTITY, ITEM_PRICE * QUANTITY AS LINE_COST.
Calculate it in your application, using a calculated field (double-click the TTable component to open the Fields Editor, add field, set the type to ftCalculated, and write code in the OnCalcEvent for that calculated field.
The first choice is usually preferable, because the DB is usually more efficient at doing those sorts of thing on sets of data than when your code does it by row instead. (Set operations are obviously more efficient than row operations.)
Ken’s answer is goes far as it goes, because the most difficult task of solving your problem is getting data from two rows at the same time in SQL. If you were using Oracle or SQL Server, you could use the analytical/windowing LAG function. With MySQL you have to do it yourself. Here are 2 articles on how to simulate LAG in MySQL
http://www.onlamp.com/pub/a/mysql/2007/03/29/emulating-analytic-aka-ranking-functions-with-mysql.html?page=1
http://explainextended.com/2009/03/12/analytic-functions-optimizing-lag-lead-first_value-last_value/
Plus there are StackOverflow questions on how to get data from the previous row.
How do I lag columns in MySQL?
Calculate delta(difference of current and previous row) in sql
I cannot offer any opinion on any of them because I seldom work with MySQL.