Quantcast
Channel: MySQL - Column value depends on values from two different tables - Database Administrators Stack Exchange
Viewing all articles
Browse latest Browse all 3

MySQL - Column value depends on values from two different tables

$
0
0

I have a MySQL database that contains these tables (* denotes primary key):

TableA:

----------------------------------------------|  *id  |  time  |  price  |  special_price  |----------------------------------------------

TableB:

-------------------------------------|  *table_a_id  |  *date  |  price  |-------------------------------------

SpecialDate:

--------------------------|  *date  |  description |--------------------------

The value of TableB.price column of each entry in TableB will be either TableA.price or TableA.special_price of the corresponding TableA entry, depending on whether TableB.date is a special date or not (whether TableB.date exists in the SpecialDate table).

This design, as it stands, doesn't feel right as every time I'm adding a record to TableB, I have to look up the date from SpecialDate to see if it's a special date or not, then look up the corresponding entry from TableA to get the value for the price column. And every time a record from SpecialDate gets added or updated, I have to go over every entry in TableB to update its price column.

I'm thinking the column TableB.price should be removed and calculated when needed but I'm not sure how to do that using SQL. I have a lot of views that depend on that price column, for example:

TableAFullView:

-----------------------------------------------------------------------------|  id  |  time  |  count_of_table_b_instances  |  sum_of_table_b_instances  |-----------------------------------------------------------------------------

Where count_of_table_b_instances is the number of TableB entries that point to this TableA entry and sum_of_table_b_instances is the sum of their prices.

With my original design, this view is simple to implement and it performs well. But if I get rid of the column TableB.price, how would I implement this view? Will the performance take a hit?


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images