我有这个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”等。
有人可以帮我吗?
最佳答案
使用表别名将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的情况,我正在使用外部联接。如果每个记录始终都具有所有maquina,则可以切换到内部联接。
无论如何,您可能要考虑另一个数据模型,在该数据模型中添加表
locale_maquina
并从id_m1
表中将单个id_m4
删除为locales
。这将使选择数据更加容易,并支持链接到位置的灵活数量的maquinas。关于mysql - MySQL语句内部联接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49173323/