左连接子查询返回Null

时间:2015-09-05 14:51:46

标签: php mysql database

我正在使用Left Join

申请Sub query & where clause

似乎没有语法错误,但我从该子查询中选择的列总是返回Null。我在SQL部分执行了相同的部分,它给了我记录。请查看查询,如果有任何可能或问题不清楚,请告诉我。

SELECT alt.userId, u.name, t.name AS teamName, alt.startDateTime, v.name AS     villageName, c.name AS clusterName, startLat, startLong, latlng.lat, latlng.long 
FROM activity_log_tim AS alt 
JOIN user AS u ON u.userId = alt.userId
JOIN team_members AS tm ON tm.memberId = u.userId
JOIN team AS t ON t.teamId = tm.teamId
JOIN village AS v ON v.villageId = alt.villageId
JOIN cluster_villages AS cv ON cv.villageId = v.villageId
JOIN cluster AS c ON c.clusterId = cv.clusterId
LEFT JOIN (SELECT lat, long,dateTime, scheduleId FROM activity_log_gps LIMIT 1) AS latlng ON latlng.scheduleId = alt.scheduleId
WHERE DATE(alt.startDateTime) = '2015-09-05' AND DATE(alt.endDateTime) = '0000-00-00' GROUP BY alt.userId ORDER BY latlng.dateTime DESC 

1 个答案:

答案 0 :(得分:0)

如果没有匹配,那么你应该执行LEFT JOIN生成NULL。因此,您可以执行INNER JOIN或使用COALESCE功能,如下所示

   SELECT alt.userId, u.name, 
t.name AS teamName, 
alt.startDateTime, 
v.name AS     
villageName, 
c.name AS clusterName, 
startLat, 
startLong, 
COALESCE(latlng.lat, 23), //Notice the use of COALESCE. If null will return 23 as default 
COALESCE(latlng.long, 32)