MySQL-需要帮助来创建以不同方式引用多个表的查询

时间:2019-02-15 13:53:06

标签: mysql

我正在努力创建一个查询以从多个表中获取数据。

这些是表格:-

enter image description here

enter image description here

enter image description here enter image description here enter image description here

我想查询基表以及其他表,以得到以下行:-

enter image description here

因此,基本表 make_ID 值需要引用 makes 表以填充结果中的 make 列。我设法完成了此查询:-

SELECT code, make, Model_ID, time
FROM makes
INNER JOIN base
ON makes.ID = base.make_ID;

但是在模型列中,我发现很棘手,因为我需要从 make 中获取结果,并使用该表选择正确的表来获取模型。因此,在第一行,我需要获取 make 结果,即 brillo ,然后使用该结果引用 brillo 使用 model_ID 中的ID来获取 finepad

如何扩展查询以执行此操作?任何见识将不胜感激。

1 个答案:

答案 0 :(得分:3)

杰里说过,您需要像这样的表make_models

+---------------+---------+----------+------------+
| make_model_id | make_id | model_id |   model    |
+---------------+---------+----------+------------+
|             1 |       1 |        1 | finepad    |
|             2 |       1 |        2 | harshpad   |
|             3 |       2 |        1 | toothbrush |
|             4 |       2 |        2 | toothpaste |
|             5 |       3 |        1 | ovenchips  |
|             6 |       3 |        2 | porkpie    |
+---------------+---------+----------+------------+
    ^^ unique identifier

因此,在您的base表中,而不是引用model_id,您可以引用make_model_id,它是唯一的,因此您可以像使用makes表一样进行联接< / p>

SELECT code, make, Model_ID, time
FROM makes
INNER JOIN base
ON makes.ID = base.make_ID
INNER JOIN make_models
   ON base.make_id = make_models.make_id
  AND base.model_id = make_models.model_id;

OR:

INNER JOIN make_models
   ON base.make_models_id = make_models.make_models_id ;

如果您无法更改模型,则可以创建一个子查询以动态构建它。了解如何根据make_id表中的ID分配makes

SELECT base.code, makes.make, make_models.model, base.time
FROM base
JOIN make
  ON base.make_id = makes.id
JOIN ( SELECT 1 as make_id, model_id,  model
       FROM brillo
       UNION ALL
       SELECT 2 as make_id, model_id,  model
       FROM colgate
       UNION ALL
       SELECT 3 as make_id, model_id,  model
       FROM mccaine
     ) as make_models
  ON base.make_id = make_models.make_id
 AND base.model_id = make_models.model_id