I have two tables- one called "orders" that has 3 columns: "id", "name", and "created_by", and the second is called "fields". The fields table holds custom fields applicable to only some kinds of orders. It has 4 columns: "id", "name", "value", and "order_id". The fields table also contains a foreign key relationship on "orders_id" to the id column in orders.
To illustrate the reason for this architecture, in one scenario an order might be for a physical product and so it needs fields for "price", "cost", and "profit". In a second scenario, the order may be for a service that carries an hourly rate, so it needs fields for "price", "hourly_rate", "profit", and "estimated hours".
Next, I created a view to join the two tables like so:
CREATE
ALGORITHM = MERGE
DEFINER = `root`@`localhost`
SQL SECURITY DEFINER
VIEW `test_view` AS
SELECT
`orders`.`id` AS `id`,
`orders`.`name` AS `name`,
`orders`.`created_by` AS `created_by`,
`fields`.`name` AS `field_name`,
`fields`.`value` AS `field_value`,
`fields`.`order_id` AS `order_id`
FROM
(`orders`
LEFT JOIN `fields` ON ((`fields`.`order_id` = `orders`.`id`)))
Results:
However, this is not the ideal format. I would prefer to use the field names as columns inside the view, but I'm not quite sure how to do that other than to use external code to manually combine the tables in the manner below.
This is what I would like to see instead:
Is there any way to accomplish this?
Thanks in advance :)