dongrong9053 2017-05-18 11:47
浏览 39
已采纳

三个表之间的关系:正确的查询和设计建议

I have three tables (MySQL):

  1. families where I define the products' families
  2. products where I define the products
  3. families_products where I relate families and products

-------------------    --------------------    ------------------------
| familyID | code |    | productID | code |    | familyID | productID |
|----------|------|    |-----------|------|    |----------|-----------|
|     1    |  p   |    |     1     |  p3  |    |    1     |     1     |
|     2    |  a   |    |     2     |  a5  |    |    1     |     3     |
|     3    |  e   |    |     3     |  p1  |    |    1     |     6     |
-------------------    |     4     |  e7  |    |    2     |     2     |
                       |     5     |  a2  |    |    2     |     5     |
                       |     6     |  p4  |    |    3     |     4     |
                       --------------------    ------------------------

I have two questions:

  1. Is this design convenient or is it better drop the families_products table putting the familyID relation directly into the table products?
  2. With a design like this one, if I have the familyID how can I retrieve the products->code? I wrote this query but a query structure like this one would work if I drop the families_products table putting the familyID relation directly into the table products as said before, not in the case of a third relational table.

'SELECT productID, code, img
 FROM products AS a
 INNER JOIN families_products AS b
 ON b.productID=a.productID
 WHERE b.familyID=' . $families[$key]["familyID"]
  • 写回答

2条回答 默认 最新

  • dongren4147 2017-05-18 11:50
    关注

    Your data structure is fine.

    If you have at most one familyID per product, then you should put the family in the products table. You should use the junction table (your structure) if a product can be part of multiple families.

    As for your query, it is fine. I would use better table aliases:

    SELECT p.productID, p.code, ??.img
    FROM products p INNER JOIN
         families_products fp
         ON f.productID = fp.productID
    WHERE fp.familyID = ' . $families[$key]["familyID"]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探