MySQL语句内连接

时间:2018-03-08 12:39:34

标签: mysql join inner-join sentence

我有这个SQL语句

SELECT
    locales.id_c,
    locales.name_p AS NombrePropietario,
    locales.surname1 AS PrimerApellido,
    locales.local_name AS Nombre_Local,
    locales.zona AS ZonaLiga,
    locales.id_m1 AS Maquina_1,
    maquinas.tipo_m AS Tipo_de_Maquina1,
    locales.id_m2 AS Maquina_2,
    maquinas.tipo_m AS Tipo_de_Maquina2,
    locales.id_m3 AS Maquina_3,
    locales.id_m4 AS Maquina_4
FROM locales
INNER JOIN maquinas
    ON locales.id_m1 = maquinas.id_m;

在这种情况下,它只显示了" Maquina_1"和" Tipo_de_Maquina1"

并且需要展示" Maquina_2"和" Tipo_de_Maquina2"," Maquina_3"和" Tipo_de_Maquina3"等等。

有人可以帮助我吗?

由于

2 个答案:

答案 0 :(得分:1)

使用表别名加入maqinas表格多重:

SELECT
  l.id_c,
  l.name_p AS NombrePropietario,
  l.surname1 AS PrimerApellido,
  l.local_name AS Nombre_Local,
  l.zona AS ZonaLiga,
  l.id_m1 AS Maquina_1,
  m1.tipo_m AS Tipo_de_Maquina1,
  l.id_m2 AS Maquina_2,
  m2.tipo_m AS Tipo_de_Maquina2,
  l.id_m3 AS Maquina_3,
  m3.tipo_m AS Tipo_de_Maquina3,
  l.id_m4 AS Maquina_4,
  m4.tipo_m AS Tipo_de_Maquina4
FROM locales l
LEFT JOIN maquinas m1 ON l.id_m1 = m1.id_m
LEFT JOIN maquinas m2 ON l.id_m2 = m2.id_m
LEFT JOIN maquinas m3 ON l.id_m3 = m3.id_m
LEFT JOIN maquinas m4 ON l.id_m4 = m4.id_m
;

如果记录没有maquina 1,2,3或4,我正在使用外部联接。如果每条记录都有所有maquinas,则可以切换到内部联接。

无论如何,您可能需要考虑另一个数据模型,在其中添加表locale_maquina并从id_m1表中删除单个id_m4locales。这样可以更轻松地选择数据并支持链接到某个位置的灵活数量的maquinas。

答案 1 :(得分:0)

您的“Tipo_de_Maquina2”错误,因为它会显示“Tipo_de_Maquina1”的相同值。

您应该遵循“Tipo_de_Maquina1”的相同INNER JOIN逻辑,以获取tipo_m的其他值。

SELECT
    locales.id_c,
    locales.name_p AS NombrePropietario,
    locales.surname1 AS PrimerApellido,
    locales.local_name AS Nombre_Local,
    locales.zona AS ZonaLiga,
    locales.id_m1 AS Maquina_1,
    m1.tipo_m AS Tipo_de_Maquina1,
    locales.id_m2 AS Maquina_2,
    m2.tipo_m AS Tipo_de_Maquina3,
    locales.id_m3 AS Maquina_3,
    m3.tipo_m AS Tipo_de_Maquina4,
    locales.id_m4 AS Maquina_4,
    m4.tipo_m AS Tipo_de_Maquina4
FROM locales
INNER JOIN maquinas AS m1
    ON locales.id_m1 = m1.id_m
INNER JOIN maquinas AS m2
    ON locales.id_m2 = m2.id_m
INNER JOIN maquinas AS m3
    ON locales.id_m3 = m3.id_m
INNER JOIN maquinas AS m4
    ON locales.id_m4 = m4.id_m;