dongyinzhi4689 2009-07-03 23:58
浏览 5
已采纳

SQL / PHP:表设计问题

I have two tables, one called "cart" and one called "items". Now I want cart to be able to store a list of "items" and quantities. So I created another table "cart_items" that has a field for the id of the template, the id of the item and the quantity.

Is this good design, or should I add another field for the id of the "cart_item"? Or is there better way to do this all together? I'm just running in trouble when I try to update my cart my cart items don't update correctly. What I'm having to do is delete all the "cart_items" attached to a cart and then re-add each "cart_item" and I can't help but think there has to be a better way to do this.

  • 写回答

4条回答 默认 最新

  • dsuvs66406 2009-07-04 00:08
    关注

    That's very good design.

    In ER (entity relationship) terms there is a many-to-many relationship between items and carts. By that I mean an item can appear in many different carts and a cart can contain many different items. "Many" in this context means "a variable number that can be more than one".

    Your cart_items table is what's called a join table and you need it to model many-to-many relationships. Added a quantity field also makes sense as does putting it on cart_items.

    You have two choices when it comes to the key:

    1. Make (cart_id, item_id) the primary key. This is called a composite primary key; or
    2. Creating an auto increment field called id. If you do this make (cart_id, item_id) a unique index to enforce uniqueness.

    Either choice is valid. Personally I prefer (2). You should also have a unique index on (item_id, cart_id) in all likelihood.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口