I have two tables. One table looks like
ORDER_ID | SHOPPER_NAME | DATE
-------------------------------
001A | Marianna | 08/09/2012
002A | Jason | 80/08/2012
and another table that has information on the order
ORDER_ID | DATA_CODE | DATA_VALUE
----------------------------------
001A | MILK_MONEY | 1.20
001A | NUM_EGGS | 22
002A | TOTAL_SPENT | 32.43
001A | TOTAL_SPENT | 42.13
I need to get several of the data codes for a specific order. How can I select SHOPPER_NAME, MILK_MONEY (DATA_VALUE where DATA_CODE = ‘MILK_MONEY’), TOTAL_SPENT and NUM_EGGS in one row? I have it working where I am doing 3 joins like
SELECT SHOPPER_NAME,
MILK.DATA_VALUE,
EGGS.DATA_VALUE,
TOTAL.DATA_VALUE
FROM GROCERIES G
JOIN ORDER_INFO MILK ON MILK.ORDER_ID=G.ORDER_ID
JOIN ORDER_INFO EGGS ON EGGS.ORDER_ID=G.ORDER_ID
JOIN ORDER_INFO TOTAL ON TOTAL.ORDER_ID=G.ORDER_ID
However this is starting to look ugly and it does not feel right to be doing multiple joins on the same table. Is there a more efficient way of doing this?
Thank you!
You could use a pivot on your 2nd table to denormalize it somewhat or you could change your db architecture by denormalizing it a bit. Look up MySQL PIVOT on stack overflow for more examples, but something like this: