Mysql使用find_in_set获取记录

时间:2014-05-13 20:15:50

标签: php mysql

我有3张桌子 (1)主题
enter image description here
(2)老师
enter image description here
(3)学生
enter image description here


我希望记录如此enter image description here


我试过下面的查询,但这不起作用

SELECT sub.name, GROUP_CONCAT( tea.name ) AS teacher,  
GROUP_CONCAT( stu.name ) AS student 
FROM subject AS sub  
LEFT JOIN teacher AS tea ON FIND_IN_SET( sub.id, tea.subject ) 
LEFT JOIN student AS stu ON FIND_IN_SET( sub.id, stu.subject ) 
GROUP BY sub.id 

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

当数据库设计不正确时,事情变得多么复杂,而且以逗号分隔字符串存储数据是最糟糕的。

您应该做的第一件事就是规范化数据,这将使生活变得简单,甚至可以优化查询。

然而,在目前的情况下,你可以尝试

select 
subject,
group_concat(distinct teacher_name) as teacher_name,
group_concat(distinct student_name) as student_name
from
(
  select
  s.name as subject,
  t.name as teacher_name,
  st.name as student_name
  from 
  subject s
  left join teacher t on find_in_set(s.id,t.subject)
  left join student st on find_in_set(s.id,st.subject)
)x
group by subject;

<强> DEMO