mysql是否可以实现动态join另外一张表?

class字段:id, class_name, student_id
1_student2_student3_student...依次类推
表*_student与表class通过student_id相关联,如:
若表class的student_id=1 则应该select * from class left join 1_student on...
若表class的student_id=2 则应该select * from class left join 2_student on...
若表class的student_id=3 则应该select * from class left join 3_student on...
...
*_student的数量和*的值是不确定的,
是否可以根据表class的字段student_id的值动态join对应的表?
实现如下的效果:
select * from class c left join {c.student_id}+'_student' on ...

阅读 6.8k
5 个回答
新手上路,请多包涵

可以
把表名作为参数

这个一般是做不到的吧,没见过这种用法

想办法得到一个所有*_student表的union,叫students,然后再去和class连接。像这样:

with students as (
    select 1 as student_id, * from 1_student union all
    select 2 as student_id, * from 2_student),
    
select *
from class left join students on 
    class.student_id = students.student_id

至于怎么得到students,要么写很多行(比如知道student_id < 10)保证所有student_id都能覆盖到,要么就根据max(class.student_id)用动态SQL生成吧。

这种情况不用做表关联了吧

查询出class的记录后,每条循环处理,根据student_id生成动态sql语句,查询*_student表的内容。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题