仅在s.id = u.summary_id时返回记录

时间:2011-04-14 18:31:44

标签: mysql sql

select
 s.id, s.description, s.improvement, s.previous_year_id, 
 s.current_year_id, s.first_name,  s.last_name, s.username, 
 s.finding, s.action, s.share, s.learned, s.timestamp, 
 d.title as department_title, 
 group_concat(g.title SEPARATOR \' | \') as strategic_goals,
 y1.year as current_year_title, y2.year as previous_year_title,
 u.summary_id, u.file_name as file_name
from
 summary s, year y1, year y2, strategic_goal_entries sge, 
 goal g, department d, uploads u
where
 s.id = sge.summary_id
and
 s.current_year_id = y1.id
and
 s.previous_year_id = y2.id
and
 sge.goal_id = g.id
and
 s.id = u.summary_id
and
 s.department_id = d.id
and
 s.department_id = '4'
group by
 s.id

这只返回摘要表中的记录,该记录表在uploads表中有相关​​记录(s.id = uploads.summary_id),其中包含uploads.summary_id字段中的值

我想要返回所有记录,无论它是否有与之关联的文件。

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

建议重构此SQL查询以使用ANSI连接。为了实现你的目标,你需要一个LEFT JOIN:

SELECT /*your columns*/
from    summary s 
INNER JOIN year y1 ON  s.current_year_id = y1.id
INNER JOIN  year y2 ON  s.previous_year_id = y2.id
INNER JOIN  strategic_goal_entries sge  ON   s.id = sge.summary_id
INNER JOIN goal g ON  sge.goal_id = g.id
INNER JOIN  department d  ON  s.department_id = d.id
LEFT JOIN  uploads u ON  s.id = u.summary_id 

WHERE  s.department_id = '4'
group by  s.id