Skip to content
Advertisement

Mysql – How to create view representing dynamic pivot

I have two database tables customers which contains data about customers with the scheme like that:

and customers_facts which keeps the customers facts in a form of fact_name and corresponding fact_value.

I want to create a pivot table which in each row will have a customer and it’s facts each as a separate column. Something like this:

I’ve found a script that allows me to create such table:

but I have an issue of how to make it so:

a) I will be able to query the pivot table

b) When I add a new entry / update an old one in one of those two original tables the pivot table will be updated

How to solve ? Is it possible ?

Advertisement

Answer

Consider the following:

Now we can create a VIEW in the manner you describe…

We can interrogate this VIEW with a simple query – e.g. SELECT customer_id FROM my_pivot WHERE name = 'Milton', however, this cannot use an index, so it’s not very efficient.

Also, because of the way in which we created the VIEW, it cannot be updated…

However, had we created the VIEW slightly differently, then it could be updated…

…but this still cannot use an index.

EDIT: To answer the question asked in comments below your question, you can do…

…although I think MySQL can’t use an index in this instance, so the longhand version might be better…

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement