views:

64

answers:

1

I now find my original table structure was not good, so want to change it. But I am having a hard time designing queries to obtain totals in rows with the new structure.

current structure:
+----------+-------+-------+-------+-------+
|   state  | shop  | item0 | item1 | item2 | 
+----------+-------+-------+-------+-------+
|    5     |  0    |   1   |   2   |   3   |
|    5     |  1    |   1   |   2   |   3   |
|    5     |  2    |   1   |   2   |   3   |
|    4     |  3    |   1   |   2   |   3   |
+----------+-------+-------+-------+-------+
(quantities of items at shop)

I want to change to these 2 tables:

shops table
+---------+--------+
| shop_id | state  |
+---------+--------+
|    0    |    5   |
|    1    |    5   |
|    2    |    5   |
|    3    |    4   |
+---------+--------+

items table
+------------+--------------+
|   shop  | item | quantity | 
+------------+--------------+
|    0    |  0   |    1     |
|    0    |  1   |    2     |
|    0    |  2   |    3     |
|    1    |  0   |    1     |
|    1    |  1   |    2     |
|    1    |  2   |    3     |
|    2    |  0   |    1     |
|    2    |  1   |    2     |
|    2    |  2   |    3     |
|    3    |  0   |    1     |
|    3    |  1   |    2     |
|    3    |  2   |    3     |
+------------+--------------+

The old layout allowed simple queries for getting totals by row:

SELECT state,SUM(item0) t0,SUM(item1) t1,SUM(item2) t2
FROM shops
WHERE state=5 

    +--------+---------+---------+----------+
    | state  |    t0   |    t1   |    t2    |
    +--------+---------+---------+----------+
    |    5   |    3    |     6   |    9     |
    +--------+---------+---------+----------+

With the new structure,
I can get the totals in column as follows:

SELECT item,SUM(quantity) total
FROM shops
LEFT JOIN items ON shop=shopid
WHERE state=5
GROUP by item
+--------+---------+
|  item  |  total  |
+--------+---------+
|    0   |    3    |
+--------+---------+
|    1   |    6    |
+--------+---------+
|    2   |    9    |
+--------+---------+

but how do I get the totals in rows:
+--------+---------+---------+----------+
| state  |    t0   |    t1   |     t2   |
+--------+---------+---------+----------+
|    4   |     1   |     2   |      3   |
|    5   |     3   |     6   |      9   |
+--------+---------+---------+----------+
+1  A: 

You might try using a few more JOINs:

SELECT S.state, 
    SUM(T0.quantity) AS "T0",
    SUM(T1.quantity) AS "T1",
    SUM(T2.quantity) AS "T2"
FROM shops AS S
LEFT JOIN items AS T0 ON S.shop_id = T0.shop_id AND T0.item=0
LEFT JOIN items AS T1 ON S.shop_id = T1.shop_id AND T1.item=1
LEFT JOIN items AS T2 ON S.shop_id = T2.shop_id AND T2.item=2
GROUP BY S.state

There might be an easier way.

Björn
Thanks, that worked.If I have a large amount of items the script will become bloated, any idea if using PHP to do the sums would be better or just keep it in mysql ?
Mahks