Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 当列不明确时,有没有办法强制Mysql使用where子句中的select列?_Php_Mysql_Sql_Laravel_Laravel 5.2 - Fatal编程技术网

Php 当列不明确时,有没有办法强制Mysql使用where子句中的select列?

Php 当列不明确时,有没有办法强制Mysql使用where子句中的select列?,php,mysql,sql,laravel,laravel-5.2,Php,Mysql,Sql,Laravel,Laravel 5.2,我有疑问: select products.* from products join companies on companies.id = products.company_id where id = 1; 查询在where子句中生成错误列“id”不明确。我知道这个列是不明确的,但我想告诉mysql只查看选定产品中的列。。所以如果我有产品。如果我有公司,产品的id将在where条款中检查。来自公司的id将在where子句中进行检查,如果我有产品,、公司。*则id将不明确 这只是一个简单的例子

我有疑问:

select products.* from products
join companies on companies.id = products.company_id
where id = 1;
查询在where子句中生成错误列“id”不明确。我知道这个列是不明确的,但我想告诉mysql只查看选定产品中的列。。所以如果我有产品。如果我有公司,产品的id将在where条款中检查。来自公司的id将在where子句中进行检查,如果我有产品,、公司。*则id将不明确

这只是一个简单的例子,查询更复杂,由ORM生成。我知道我可以用

select products.id as products_id from products
where products.id = 1;
然后使用

where products_id  = 1
或者我可以用

select products.id as products_id from products
where products.id = 1;

但这不适合我的需要,因为查询是由orm生成的。有什么想法吗?

您可以在编写时指定要从哪个表中使用id:

select products.* from products
join companies on companies.id = products.company_id
where products.id = 1;
WHERE products.id = 1
使用eloquent时,可以使用DB::raw:

DB::table('products')
    ->select(DB::raw('products.*'))
    ->join('companies', DB::raw('companies.id'), '=', DB::raw('products.company_id'))
    ->where(DB::raw('products.id'), '=', 1)
    ->get()
;

您尝试过WHERE products.id=1吗?这是一个糟糕的示例。但是-您可以使用子查询。@出现此问题的原因是,我将子查询更改为联接查询,因为它们的速度慢了1000倍……子查询是一种通用解决方案。如果你想要一个具体的解决方案,你的例子应该更具体。我不明白的是:在某个时候,你必须决定在SELECT中使用哪个表。所以你有一个类似->选择{$tableName}.*的代码。为什么不能对WHERE子句使用相同的变量:->WHERE{$tableName}.id,1?请阅读问题。OP不想在where子句中硬编码表前缀。@他没有写那个。他只是写道,他不知道如何使用eloquent实现这一点。与另一个答案相同:WHERE子句中的表名是硬编码的,这不是OP想要的。没有任何信息表明他不能/不想硬编码表。他只是用了一个信息,很有说服力。他在我的回答和你的否决票之后写了这篇评论。答案没有错。即使它不是他想要的,它也能工作——如果他不写它,就不可能预测他想要什么。