【问题标题】:create table column based on another table column value in sql根据sql中的另一个表列值创建表列
【发布时间】:2015-12-02 03:37:30
【问题描述】:

是否有可能基于另一个表列值创建表列? 现有表(geozone)看起来像这样,它不是固定的(可以包含更多的 id 和名称)

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

我正在尝试从 php 页面创建一个新页面

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`)
        )");

上面的查询成功创建了运输表,但这不是我需要的,我如何创建具有地理区域 id 的 id 的 shipping_cost 列?
示例:shipping_cost_1、shipping_cost_2 和 shipping_cost_3

【问题讨论】:

  • 是的,这是可能的,但在运行时创建表/列是糟糕的设计。 See my today answer
  • 它只有在点击安装时才会执行(不需要解释),顺便问一下我如何编写查询?
  • 你们有多少个送货区?也许是一个糟糕的设计
  • @drew,我可以说这取决于他们有多少,可以少/多。如果他们愿意,他们也可以添加/删除地理区域,我只是把 3 作为我的问题的例子
  • 问题是,如果你有 26 个,并且你的生活是在 ALTER TABLE 中度过的,并且使用 NULLS,以及所有产品级别的维护。它没有规模,而且打扫房间会很麻烦。无论如何,这都是一件苦差事,关键是要让它快速且最小化。

标签: php mysql sql create-table


【解决方案1】:

听起来运费取决于产品及其发送到的地理区域,这意味着需要将geozone_id 列添加到您的shipping_cost 表中。还要在 (geozone_id,product_id) 上添加一个唯一约束,因为每个唯一对应该只有一个运费。

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
)

然后您可以选择每个产品/地理区域对的成本:

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

【讨论】:

    猜你喜欢
    • 2018-06-20
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 2020-04-28
    • 2018-10-24
    • 2023-02-11
    • 1970-01-01
    • 2023-02-23
    相关资源
    最近更新 更多