我尝试运行SQL查询并收到错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'logs.user_ID' in 'on clause'
查询是这样的:
SELECT
logs.*, users.first_Name, users.last_Name, users.middle_Name
FROM logs
LEFT JOIN users ON (logs.user_ID = users.ID)
WHERE logs.record_Type = 'issues' AND logs.record_ID = 33
当我在服务器上手动运行查询时,它返回正确的结果,但在PHP代码中没有快乐。
当我删除" WHERE"它在PHP中运行得很好。此时我怀疑是MySQL语法问题,但我无法弄明白。
查询生成代码:
public static function prepareQuery() {
if(self::$distinct) {
$query = array("SELECT DISTINCT");
} else {
$query = array("SELECT");
}
if (count(self::$_fields) == 0) {
$query[] = "*";
} else {
$query[] = implode(", ", self::$_fields);
}
if (!empty(self::$_table)) {
$query[] = "FROM " . self::$_table;
}
if (!empty(self::$_join)) {
foreach (self::$_join as $aJoin) {
list($table, $field, $expression, $value) = $aJoin;
$sJoin = "LEFT JOIN " . $table . " ON (" . $field . " " . $expression . " " . $value . ")";
$aJoins[] = $sJoin;
}
$query[] = implode(" \n", $aJoins);
}
if (!is_null(self::$_expression)) {
$query[] = "WHERE " . self::$_expression;
}
self::$_query = implode(" \n", $query);
self::reset();
}
我在这称呼该方法:
public static function get($recordType = "all", $recordID = "0", $userID = "0") {
Select::setTable("logs");
$aFields = array("logs.*", "users.first_Name", "users.last_Name", "users.middle_Name");
Select::addField($aFields);
if ($recordType != "all") {
Select::customExpression("logs.record_Type = '$recordType' AND logs.record_ID = $recordID");
} else {
if ($userID != "0") {
Select::customExpression("logs.user_ID = $userID");
}
}
Select::join("users", "logs.user_ID", "=", "users.ID");
Select::prepareQuery();
Str::print_var(Select::$_query);
Select::execute();
$oResult = Select::$result;
return $oResult->fetchAll(PDO::FETCH_CLASS, "Log");
}
答案 0 :(得分:0)
这在技术上不是一个答案,但我解决了这个问题。 生成的SQL是:
SELECT
logs.*, users.first_Name, users.last_Name, users.middle_Name
FROM logs
LEFT JOIN users ON logs.user_ID = users.ID
WHERE logs.record_Type = 'issues' AND logs.record_ID = 33
我更改了“on”子句从“logs.user_ID”删除表引用,它工作得很好。当我在服务器上运行这个SQL时,它突出显示了单词LOGs,所以我怀疑LOGS是一些特殊的关键字。 虽然问题已经解决,但是这个错误的原因对我来说仍然是个谜,所以我很感激有关这个问题的任何意见。