MySQL在多个可能的表中选择相关数据

时间:2015-07-22 00:43:49

标签: mysql sql select relational-database

我有8个表,组,项和6个各种类型表。组包含多个项目,并且项目具有特定类型(项目和类型之间的关系为1-1)。

样本数据如下:

组表:

----------------------------
| groupID (PK) | groupName |
----------------------------
| 1            | Buying    | 
| 2            | Selling   |
----------------------------

项目表:

--------------------------------------------
| itemID (PK) | groupID (FK) | itemName    |
--------------------------------------------
| 10          | 1            | Rugby Ball  |
| 11          | 2            | Kettle      |
| 12          | 2            | Soccer Ball |
| 13          | 1            | Toaster     |
| 14          | 1            | Couch       |
--------------------------------------------

类型表: type1(家电):

--------------------------------------------------
| appliancesID (PK) | itemID (FK) | energyRating |
--------------------------------------------------
| 20                | 11          | 5            |
| 21                | 13          | 3            |
--------------------------------------------------

type2(Balls):

--------------------------------------------------------
| ballID (PK) | itemID (FK) | inflateTo | Size         |
--------------------------------------------------------
| 33          | 10          | 20 psi    | Junior       |
| 34          | 12          | 40 psi    | Professional |
--------------------------------------------------------

我正在尝试执行一个返回包含所有项目及其相关类型信息的组的查询。

SELECT * 
FROM groups g, items i, type1 t1, type2 t2, type3 t3, type4 t4, type5 t5, type6 t6
WHERE g.groupID = i.groupID
AND
// Now determine which type table has the related record
// e.g. if related item type1: 
// AND i.itemID = t1.itemID
AND g.groupID = 2

作为查询的一部分,对于组中的每个项目,我需要返回该项目,包括其相关的类型记录。

上述查询结果的示例数据为:

----------------------------------------------------------------------------------------------------------------
| groupID | groupName | itemID | itemName    | applianceID | energyRating | ballID  | inflateTo | Size         |
----------------------------------------------------------------------------------------------------------------
| 2       | Selling   | 11     | Kettle      | 20          | 5            | //empty | //empty   | //empty      | 
| 2       | Selling   | 12     | Soccer Ball | //empty     | //empty      | 34      | 40 psi    | Professional |
----------------------------------------------------------------------------------------------------------------   

如何构建查询以包含组中每个项目的正确类型信息?

0 个答案:

没有答案