将属性名称加入MySQL

时间:2015-08-20 16:04:09

标签: mysql sql database relational-database rdms

我需要创建一个表来存储属性的多个值:

Table Main
____________________________________________________
| Person      |       Hobbies      |TimeSpent(hrs) |
----------------------------------------------------
|   John      | gardening, guitar  |  2,4          |
|   Harry     |     programming    |  8            |
----------------------------------------------------

在线查看之后,解决方案似乎涉及单独的表并加入它们:

Table John
| Hobbies     | TimeSpent |
---------------------------
|   Gardening |    2      |
|   Guitar    |    4      |
---------------------------

Table Harry
| Hobbies     | TimeSpent |
---------------------------
|  Programming|    8      |
---------------------------

两个问题:

  1. 这是正确的方法吗?约翰和哈利的表格预计会很大。
  2. 如何为表格名称作为各自名称的每个人自动创建一个表格,如何在表格主页中找到John的表格“John”?

1 个答案:

答案 0 :(得分:1)

我认为以下设计可能适合您。

[PERSON]

PERSON ID(PRIMARY KEY), NAME

[HOBBY]

HOBBY ID(PRIMARY KEY), HOBBY

[PERSON_HOBBY]

PERSON_ID(PRIMARY KEY,FOREIGN KEY TO PERSON), HOBBY_ID(PRIMARY KEY,FOREIGN KEY TO HOBBY), TIME_SPENT

以下陈述适用于新设计:

SELECT p.NAME, GROUP_CONCAT( h.HOBBY ORDER BY ph.HOBBY_ID ASC SEPARATOR ',') AS 'HOBBIES', 
GROUP_CONCAT( ph.TIME_SPENT ORDER BY ph.HOBBY_ID ASC SEPARATOR ',') AS 'HOURS SPENT' 
FROM PERSON_HOBBY ph
LEFT JOIN PERSON p ON p.PERSON_ID = ph.PERSON_ID
LEFT JOIN HOBBY h ON h.HOBBY_ID = ph.HOBBY_ID
GROUP BY ph.PERSON_ID;