将1个表格行中的多个ID查询到1个查询中的另一张表

时间:2018-07-22 21:33:44

标签: mysql sql

我在MySQL中有2个表
表1
ID |名称| group_1 | group_2 | group_3

表2
ID | group_name | Group_location

我想获取表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 enter image description here

2 个答案:

答案 0 :(得分:2)

这是您想要的吗?

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

答案 1 :(得分:1)

尝试一下;

 SELECT t1.name
      , t21.group_name
      , t22.group_name
      , t23.group_name 
   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);