SQLSTATE [42S22]:找不到列:1054 'where 子句为啥'中的未知列'4'我找不到错误

Posted

技术标签:

【中文标题】SQLSTATE [42S22]:找不到列:1054 \'where 子句为啥\'中的未知列\'4\'我找不到错误【英文标题】:SQLSTATE[42S22]: Column not found: 1054 Unknown column '4' in 'where clause why' i cannot find the mistakeSQLSTATE [42S22]:找不到列:1054 'where 子句为什么'中的未知列'4'我找不到错误 【发布时间】:2021-06-28 12:34:15 【问题描述】:

我的 php/laravel 代码中有一个 select wuery 问题是当我运行它时会出现此错误

 SQLSTATE[42S22]: Column not found: 1054 Unknown column '4' in 'where clause'
where (`element_value`.`p_id` = `4`))

这是我的查询

DB::table('value_tbl')
    ->select(DB::raw("CONCAT(values.value_name,'/',element_value.qan) AS full_value"))
    ->leftJoin('element_value','element_value.element_id','value.element_id')
    ->where (['element_value.p_id'=>$a->p_id])->get()->pluck('full_value')->toArray())

【问题讨论】:

element_value.p_id改成element_value.p_id 什么??你是什​​么意思 where (element_value.p_id = 4)) 到 where (element_value.p_id = 4)) 你已经连接了两个字符串,现在它读取 element_valuep_id 而不是element_value.p_id where (element_value.p_id` = 4))` 这一行在页面返回的错误中..上面是我写的代码 我的所有查询中都没有数字 4 【参考方案1】:

如果要使用运算符,where 函数需要三个参数:第一个是列名,第二个是运算符,第三个是要比较的值。

将您的条件更改为如下所示

->where('element_value.p_id', '=', $a->p_id)
// or, because you are making an exact match, do this
->where('element_value.p_id', $a->p_id)

您现在的代码变得混乱,因为您告诉 Laravel 您正在通过使用数组作为 where 第一个参数来创建多个 where 条件。 然后,Laravel 获取该数组的值并尝试将其转换为列、运算符和值——就像上面的 sn-p 所做的那样。

如果您真的想使用数组,您需要执行以下操作:

->where([
    ['element_value.p_id', '=', $a->p_id]
])
// or, because you are making an exact match, do this
->where([
    ['element_value.p_id', $a->p_id]
])

注意我们是如何传递两组数组的? 这是因为 Laravel 要么希望每个参数分开,要么希望包含正确签名的数组。


如需更详细的答案; the signature 是这样的

public function where($column, $operator = null, $value = null, $boolean = 'and')

如果$column 是一个数组,则假定将一个array-of-arrays 传递到该方法中,并且每个子数组将有效地分布在上述签名中。

当您将单个数组传递给该方法时,Laravel 正在获取 4 的值,然后将其用作 $column。 这是因为您为该数组使用了键值对,因此您使用的列名实际上被忽略了。

这个方法的另一个有趣的地方是它有following snippet:

// If the given operator is not found in the list of valid operators we will
// assume that the developer is just short-cutting the '=' operators and
// we will set the operators to '=' and set the values appropriately.
if ($this->invalidOperator($operator)) 
    [$value, $operator] = [$operator, '='];

这允许我们不传入运算符,Laravel 将假设我们希望使用 = 来代替。 这就是我能够从上面的示例中省略它的原因。

【讨论】:

哪里 ('element_value.p_id','=',$a->p_id) 如果要使用运算符, where 函数需要 3 个参数:首先是列的名称。第二个是运算符,第三个是要比较的值。 你也可以完全否定@​​987654331@。关键是,它不应该是 where 子句中的键值对。

以上是关于SQLSTATE [42S22]:找不到列:1054 'where 子句为啥'中的未知列'4'我找不到错误的主要内容,如果未能解决你的问题,请参考以下文章

SQLSTATE [42S22]:找不到列:1054 未知列 '0' where 子句

SQLSTATE [42S22]:找不到列:1054 未知列 laravel 5.1

SQLSTATE [42S22]:找不到列:1054 'where 子句'中的未知列'user_id'

Laravel 删除数据 - SQLSTATE [42S22]:找不到列:1054 未知列

SQLSTATE [42S22]:找不到列:1054 未知列 'role_not' 错误

SQLSTATE [42S22]:找不到列:在 laravel livewire 项目中