Search code examples
phpmysqlsqlcreate-table

create table column based on another table column value in sql


is there any possibility to create table column base on another table column value? existing table(geozone) would look like this and it is not fixed(can contain more id and name)

id | name
1  | UK
2  | CANADA
3  | JAPAN

and i am trying to create new one from php page

mysql_query("CREATE TABLE shipping (
        `id` int(11) NOT NULL auto_increment,
        `product_id` int(11) NOT NULL,
        `shipping_cost` decimal(15,2) NOT NULL,
        PRIMARY KEY  (`id`),
        UNIQUE KEY `id` (`id`)
        )");

the query above create shipping table successfully but that's not what i need, how can i create shipping_cost column has an id of geozone id?
example: shipping_cost_1, shipping_cost_2 and shipping_cost_3


Solution

  • It sounds like the shipping cost depends on the product and the geozone it's sent to, which means a geozone_id column needs to be added to your shipping_cost table. Also add a unique constraint on (geozone_id,product_id) because each unique pair should have only one shipping cost.

    CREATE TABLE shipping (
        `id` int(11) NOT NULL auto_increment,
        `geozone_id` int(11) NOT NULL, -- specify which geozone this cost is for
        `product_id` int(11) NOT NULL,
        `shipping_cost` decimal(15,2) NOT NULL,
        PRIMARY KEY  (`id`),
        -- UNIQUE KEY `id` (`id`), -- Not necessary because Primary keys are already unique 
        UNIQUE KEY `product_id_geozone_id` (`product_id`,`geozone_id`) -- each product, geozone can only have 1 cost
    )
    

    Then you can select the cost for each product/geozone pair with a join:

    select geozone.name, product.name,
    shipping.shipping_cost
    from products
    join shipping on shipping.product_id = product.id
    join geozone on shipping.geozone_id = geozone.id