【问题标题】:Creating a Table in SQL, where each tuple can have mutiple values在 SQL 中创建一个表,其中每个元组可以有多个值
【发布时间】:2014-10-17 17:05:12
【问题描述】:

我尝试在 SQL 中使用 Create Table 创建一个表, 一个人可以在多个地方工作,一个地方可以有多个人在工作, 这是我正在尝试的,我确​​定它不正确

      create table ( person char(15), place char(15), salary int)

现在由于一个人可以在多个地方工作,如果元组位置有多个值,我会感到困惑, 如果是。我该怎么做 提前致谢

【问题讨论】:

  • 供将来参考:关系数据库中的元组永远不会有不同数量的列。这是关系数据库基本结构的一部分——一个表有一定数量的列,并且该表中的任何元组都不会有不同的列数。
  • 不相关但:您很可能想使用char(xxx)。该数据类型会用空格填充到定义的长度。

标签: mysql sql database create-table


【解决方案1】:

它被称为 n 到 m 关系。使用 3 张桌子

persons table
-------------
id    int
name  varchar


places table
------------
id    int
name  varchar


place_persons table
-------------------
place_id   int
person_id  int

【讨论】:

    【解决方案2】:

    您应该创建三个单独的表:

    "persons"
    int ID (primary key, auto-increment)
    varchar username
    varchar email ... (all other info needed)
    
    "places"
    int ID (primary key, auto-increment)
    varchar name
    etc.
    

    而第三张表给你的是两者之间的关系:

    "person_places" (or place_persons, depends on what you like)
    int ID (primary key, auto-increment)
    int place_id (linked to the ID of the "places" entry)
    int person_id (linked to the ID of the "persons" entry)
    

    这样,每次有人开始在新地方工作时,您只需在“person_places”中添加一个条目。当他们离开一个地方,或者一个地方倒闭或其他什么时,同样的事情,你只需要触摸“person_places”表。

    另外,这样一个人可以在多个地方工作,就像一个地方可以有几个人在里面工作一样。

    【讨论】:

      【解决方案3】:

      这不是规范化的,但是可以使用它,因为您只有 3 列,并且规范化会增加更多令人头疼的连接和额外的列来定义关系。

      假设 PersonA 在 PlaceA 和 PlaceB 都工作。 PersonB 也在这两个地方工作,但薪水不同,那么您的数据将是这样的

      insert into Yourtable values 
      ('PersonA','PlaceA',1000),
      ('PersonA','PlaceB',2000),
      ('PersonB','PlaceA',1100),
      ('PersonB','PlaceB',1200),
      ('PersonC','PlaceA',1000)
      

      如果您想知道 PersonA 在多少个地方工作,那么您查询的将是

      select place from YourTable where person = 'PersonA'
      

      这样你就不需要在同一个元组中保存多个值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-16
        • 2016-09-13
        • 2017-01-12
        • 1970-01-01
        相关资源
        最近更新 更多