简体   繁体   English

当列不明确时,有什么方法可以强制Mysql在where子句中的select中使用列?

[英]Any way to force Mysql to use column from select in where clause when column is ambiguous?

I have query: 我有查询:

select products.* from products
join companies on companies.id = products.company_id
where id = 1;

query generates error "Column 'id' in where clause is ambiguous". 查询生成错误“ where子句不明确的列'id'”。 I know that column is ambiguous, but I want tell mysql to look only columns in select "products. ". 我知道该列是不明确的,但是我想告诉mysql在选择“产品”中仅查找列 So if I have "products. " id from products will be examined in where clause, if I have "companies. " id from companies will be examined in where clause, if I have "products. , companies.*" only then id will be ambiguous. 因此,如果我有“产品 ”,则将在where子句中检查产品的ID 如果我有“公司”,则将在where子句中检查来自公司的ID,如果我具有“产品。 ,公司。*”,则id将只有模棱两可。

This is just plain example, query is more complicated and generated by ORM. 这只是简单的示例,查询更为复杂,由ORM生成。 I know I can use 我知道我可以用

select products.id as products_id from products

and then use 然后使用

where products_id  = 1

or I can use 或者我可以使用

where products.id = 1;

but this does not fit to my needs because query is generated by orm. 但这不符合我的需求,因为查询是由orm生成的。 Any ideas ? 有任何想法吗 ?

You can specify from which table you want to use id as you wrote: 您可以在编写时指定要从哪个表中使用ID:

WHERE products.id = 1

When using eloquent you can do it in using DB::raw: 当使用口才时,可以使用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()
;
select products.* from products
join companies on companies.id = products.company_id
where products.id = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM