首页 > 解决方案 > 在 1 个查询中将 1 个表行中的多个 ID 查询到另一个表

问题描述

我在 MySQL
table1
ID|name|group_1|group_2|group_3

Table2
ID|group_name|Group_location中有 2 个表

我想获取表 1 ID 并显示所有数据而不是 tableID。我正在尝试使用这样的连接

SELECT table1.name, table2.group_1, table1.group_2, table1.group_3
FROM tabl1 JOIN table2 on table1.group_1 = table2.ID  AND
table1.group_2 = table2.ID   AND table1.group_3 = table2.ID
WHERE table1.ID IN (868) 
ORDER BY FIELD(table1.ID,868);

它只返回结果中的 ID,但我希望它返回 table2 group_name 在此处输入图像描述

标签: mysqlsql

解决方案


这是你想要的吗?

SELECT t1.name, t21.group_1, t22.group_2, t23.group_3
FROM table1 t1 LEFT JOIN
     table2 t21
     ON t1.group_1 = t21.ID LEFT JOIN
     table2 t21
     ON t1.group_2 = t22.ID LEFT JOIN
     table2 t21
     ON t1.group_3 = t23.ID 
WHERE t1.ID IN (868) 
ORDER BY FIELD(t1.ID, 868);

LEFT JOIN在任何参考列是 的情况下使用NULL


推荐阅读