我从mySQL数据库中选择一些数据。我想只选择project_id不为NULL或为空的数据:
$result = $db->query('SELECT *
FROM data
LEFT JOIN projects ON data.project=projects.project_id
GROUP BY data.id
WHERE projects.project_id IS NOT NULL
ORDER BY data.id DESC
')->fetchAll(PDO::FETCH_ASSOC);
但是我收到一条错误消息:
未捕获的PDOException:SQLSTATE [42000]:语法错误或访问 违规:1064您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以获得正确的语法 在第21行'WHERE projects.project_id IS NOT NOT ORDER BY d'附近使用
答案 0 :(得分:2)
where
子句出现在group by
我相信您已经拥有主键,因此您无需明确添加null
支票。如果您只需要匹配的数据集,请使用inner join
代替left join
。
答案 1 :(得分:1)
这应该有效,您只是没有使用where
和order by
$result = $db->query('SELECT *
FROM data
LEFT JOIN projects ON data.project=projects.project_id
WHERE projects.project_id IS NOT NULL
GROUP BY data.id
ORDER BY data.id DESC
')->fetchAll(PDO::FETCH_ASSOC);
答案 2 :(得分:1)
查询应该有一个正确的语法,因为group by将在where之前。 查询应该是
SELECT * FROM data
LEFT JOIN projects ON data.project=projects.project_id
WHERE projects.project_id IS NOT NULL
GROUP BY data.id
ORDER BY data.id DESC