我使用以下查询来获取数据,但现在我需要再次加入同一个表4次或更多次,所以我想找到替代方法。
SELECT t1.id,t1.name,t2.name as name2,t3.name as name3,t4.name as name4....
FROM first_table as t1
left join second_table as t2 on t2.code = t1.f_name,
left join second_table as t3 on t3.code = t1.l_name,
left join second_table as t4 on t4.code = t1.a_name,
.......
.....
.....
和很多联接所以如何以更好的方式(高效)获得相同的结果?
答案 0 :(得分:2)
您可以尝试使用此查询:
SELECT
t1.id,
t1.name,
MAX(CASE WHEN t2.code = t1.f_name THEN t2.name END) AS name2,
MAX(CASE WHEN t2.code = t1.l_name THEN t2.name END) AS name3,
MAX(CASE WHEN t2.code = t1.a_name THEN t2.name END) AS name4
FORM
first_table AS t1 LEFT JOIN second_table AS t2
ON t2.code IN (t1.f_name, t1.l_name, t1.a_name)
GROUP BY
t1.id,
t1.name