join子句不显示所有结果

时间:2012-12-31 09:41:57

标签: mysql sql join foreign-keys

这是一个非常奇怪的问题。 我有3个表,都在agent_id上有关键关系。

现在这个查询:

select DATE_FORMAT(created_on,"%d/%m/%y") as date
from logs
where agent_id = "18"
and log_status="1"
and date_format(created_on,"%m/%y") = "12/12"
group by YEAR(created_on), MONTH(created_on), DAY(created_on) desc

确实是它所支持的,它返回3行:

date
31/12/12
30/12/12
26/12/12

但是,当我加入其他2个表格时,它会排除31/12/12的日期。这是查询:

select  DATE_FORMAT(l.created_on,"%d/%m/%y") as date
from logs l
join logs_rewards lr on l.id = lr.related_log_id 
join agents a on a.id = l.agent_id 
where l.log_status = "1" 
and DATE_FORMAT(l.created_on,"%m/%y") = '12/12'
AND l.agent_id = '18' 
group by YEAR(l.created_on), MONTH(l.created_on), DAY(l.created_on) desc

返回:

date
30/12/12
26/12/12

我无法弄清楚为什么会这样。有什么帮助吗?

我已尝试将AND l.agent_id = '18'更改为AND a.id = '18'但结果相同。

2 个答案:

答案 0 :(得分:0)

您可能希望将 JOIN 替换为 LEFT JOIN ,以便从日志中获取所有结果。

答案 1 :(得分:0)

这是因为数据未映射到所有3个表中。

以下查询将有效

select  DATE_FORMAT(l.created_on,"%d/%m/%y") as date
from logs l
left join logs_rewards lr on l.id = lr.related_log_id 
left join agents a on a.id = l.agent_id 
where l.log_status = "1" 
and DATE_FORMAT(l.created_on,"%m/%y") = '12/12'
AND l.agent_id = '18' 
group by YEAR(l.created_on), MONTH(l.created_on), DAY(l.created_on) desc